Create My First Program in PHP Core Language

Oct 31, 2025 - 11:27
 0  138749
Create My First Program in PHP Core Language

Building Your First PHP Program: A Beginner's Guide

PHP is one of the most popular server-side scripting languages, powering millions of websites including Facebook, WordPress, and Wikipedia. If you're new to web development, creating your first PHP program is an exciting milestone. This guide will walk you through building a simple but functional PHP application from scratch.

Prerequisites

Before we begin, make sure you have:

  • A local server environment (XAMPP, WAMP, or MAMP)

  • A code editor (VS Code, Sublime Text, or PHPStorm)

  • Basic understanding of HTML

Step 1: Setting Up Your Development Environment

First, let's set up your workspace:

  1. Install XAMPP (Windows) or MAMP (Mac)

  2. Start the Apache server

  3. Navigate to your htdocs folder (XAMPP) or www folder (MAMP)

  4. Create a new folder called my-first-php

Step 2: Creating Your First PHP File

Create a new file called index.php in your my-first-php folder and open it in your code editor.

Basic PHP Syntax

Every PHP script starts with <?php and ends with ?>:

php
<?php
    // Your PHP code goes here
?>

Step 3: Building a Simple "Hello World" Program

Let's start with the classic beginner program:

php
<!DOCTYPE html>
<html>
<head>
    <title>My First PHP Program</title>
</head>
<body>
    <h1>Welcome to PHP!</h1>
    
    <?php
        // Display a greeting message
        echo "<h2>Hello, World!</h2>";
        echo "<p>Today is " . date("Y-m-d") . "</p>";
    ?>
    
    <p>This is my first PHP program running successfully!</p>
</body>
</html>

Step 4: Adding Variables and User Interaction

Let's make our program more interactive by collecting user input through a form:

php
<!DOCTYPE html>
<html>
<head>
    <title>Personal Greeting Generator</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
        .container { background: #f4f4f4; padding: 20px; border-radius: 8px; }
        input, button { padding: 10px; margin: 5px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Personal Greeting Generator</h1>
        
        <?php
        // Check if form was submitted
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            // Get user input
            $name = htmlspecialchars($_POST['name']);
            $age = htmlspecialchars($_POST['age']);
            $color = htmlspecialchars($_POST['color']);
            
            // Display personalized greeting
            echo "<div style='background: $color; padding: 15px; border-radius: 5px; color: white;'>";
            echo "<h2>Welcome, $name!</h2>";
            echo "<p>You are $age years old.</p>";
            
            // Simple age-based message
            if ($age < 18) {
                echo "<p>You're young and full of potential!</p>";
            } elseif ($age < 30) {
                echo "<p>You're in the prime of your life!</p>";
            } else {
                echo "<p>You have wisdom and experience!</p>";
            }
            
            echo "</div>";
            echo "<br><a href='".$_SERVER['PHP_SELF']."'>Create Another Greeting</a>";
        } else {
            // Display the form
        ?>
        
        <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
            <label for="name">Your Name:</label><br>
            <input type="text" id="name" name="name" required><br><br>
            
            <label for="age">Your Age:</label><br>
            <input type="number" id="age" name="age" required><br><br>
            
            <label for="color">Favorite Color:</label><br>
            <input type="color" id="color" name="color" value="#3498db"><br><br>
            
            <button type="submit">Generate Greeting</button>
        </form>
        
        <?php } ?>
    </div>
</body>
</html>

Step 5: Creating a Simple Task Manager

Let's build a more practical application - a basic task manager:

php
<?php
// Simple task manager
session_start();

// Initialize tasks array if it doesn't exist
if (!isset($_SESSION['tasks'])) {
    $_SESSION['tasks'] = [];
}

// Add new task
if (isset($_POST['new_task']) && !empty($_POST['new_task'])) {
    $newTask = [
        'id' => uniqid(),
        'text' => htmlspecialchars($_POST['new_task']),
        'completed' => false,
        'created_at' => date('Y-m-d H:i:s')
    ];
    $_SESSION['tasks'][] = $newTask;
}

// Mark task as completed
if (isset($_POST['complete_task'])) {
    $taskId = $_POST['complete_task'];
    foreach ($_SESSION['tasks'] as &$task) {
        if ($task['id'] === $taskId) {
            $task['completed'] = true;
            break;
        }
    }
}

// Delete task
if (isset($_POST['delete_task'])) {
    $taskId = $_POST['delete_task'];
    $_SESSION['tasks'] = array_filter($_SESSION['tasks'], function($task) use ($taskId) {
        return $task['id'] !== $taskId;
    });
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Simple Task Manager</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
        .task-form { margin-bottom: 30px; }
        .task-item { padding: 10px; margin: 5px 0; background: #f9f9f9; border-left: 4px solid #3498db; }
        .completed { text-decoration: line-through; opacity: 0.6; border-left-color: #27ae60; }
        button { margin-left: 10px; padding: 5px 10px; }
    </style>
</head>
<body>
    <h1>Simple Task Manager</h1>
    
    <div class="task-form">
        <form method="POST">
            <input type="text" name="new_task" placeholder="Enter a new task..." required style="padding: 10px; width: 70%;">
            <button type="submit" style="padding: 10px 20px;">Add Task</button>
        </form>
    </div>
    
    <div class="task-list">
        <h2>Your Tasks (<?php echo count($_SESSION['tasks']); ?>)</h2>
        
        <?php if (empty($_SESSION['tasks'])): ?>
            <p>No tasks yet. Add your first task above!</p>
        <?php else: ?>
            <?php foreach ($_SESSION['tasks'] as $task): ?>
                <div class="task-item <?php echo $task['completed'] ? 'completed' : ''; ?>">
                    <span><?php echo $task['text']; ?></span>
                    <small>(Added: <?php echo $task['created_at']; ?>)</small>
                    
                    <?php if (!$task['completed']): ?>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="complete_task" value="<?php echo $task['id']; ?>">
                            <button type="submit">Complete</button>
                        </form>
                    <?php endif; ?>
                    
                    <form method="POST" style="display: inline;">
                        <input type="hidden" name="delete_task" value="<?php echo $task['id']; ?>">
                        <button type="submit" style="background: #e74c3c; color: white;">Delete</button>
                    </form>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</body>
</html>

Key PHP Concepts Demonstrated

  1. Variables and Data Types: Storing user input in variables

  2. Forms Handling: Processing POST data

  3. Conditional Statements: Using if/else for logic

  4. Sessions: Maintaining state across page loads

  5. Arrays: Storing and manipulating task data

  6. String Manipulation: Formatting and displaying text

  7. Security: Using htmlspecialchars() to prevent XSS attacks

Testing Your Program

  1. Save your files with .php extension

  2. Ensure your local server (Apache) is running

  3. Open your web browser and navigate to:

    text
    http://localhost/my-first-php/index.php

Next Steps

After mastering these basics, consider learning:

  • PHP functions and classes

  • Database integration with MySQL

  • Form validation and security

  • Object-oriented PHP

  • PHP frameworks like Laravel or Symfony

Common Issues and Solutions

  • White screen: Check for syntax errors and enable error reporting

  • Form not submitting: Verify form method is POST and action is correct

  • Variables not displaying: Ensure you're using echo or print

Congratulations! You've just built your first PHP applications. Remember that programming is a skill developed through practice, so keep experimenting and building new projects. Happy coding!

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow

MA Hussain Amjad Hussain: Architect of Truth in the Realm of Fact In the intricate tapestry of human experience, where shadow often meets light, Amjad Hussain stands as a dedicated chronicler of reality. His is a world built on the unshakeable foundations of fact, a pursuit he undertakes with the dual tools of a journalist's discerning eye and a writer's compelling narrative skill.