Skip to main content

Course Progress

Loading...

Creating a Simple PHP Script

Duration: 60 minutes
Module 1: Introduction to PHP

Learning Objectives

  • Understand PHP basics
  • Set up PHP development environment
  • Write server-side code
  • Prepare for WordPress development

Introduction to PHP Scripts

PHP (PHP: Hypertext Preprocessor) is a server-side scripting language designed specifically for web development. Unlike HTML, CSS, and JavaScript that run in the browser, PHP code runs on the web server and generates HTML that is then sent to the client's browser. This makes PHP perfect for creating dynamic web pages that can interact with databases, process forms, manage sessions, and much more.

Browser Web Server PHP Engine HTTP Request HTTP Response (HTML)

In this lesson, we'll learn how to create a simple PHP script that demonstrates basic syntax and functionality. By the end, you'll understand how to write, save, and run PHP code in your local development environment.

Polya's Problem Solving Approach for Creating a PHP Script

Step 1: Understand the Problem

Before writing any code, let's clarify what we're trying to achieve:

  • Create a simple PHP script that demonstrates basic PHP functionality
  • Make sure the script runs correctly in a local server environment
  • Display dynamic content that wouldn't be possible with just HTML

Input: PHP code we will write

Output: HTML content generated by our PHP code and displayed in a browser

Step 2: Devise a Plan

Let's break down the process into manageable steps:

  1. Verify our local server environment is working (XAMPP, MAMP, Docker, etc.)
  2. Create a new PHP file in the correct directory
  3. Write basic PHP syntax (opening/closing tags, echo statements)
  4. Add variables and demonstrate data types
  5. Implement control structures (conditionals, loops)
  6. Display dynamic content (current date/time, server info)
  7. Run and test our script in a browser

Step 3: Execute the Plan

Now let's follow our plan step by step:

Setting Up Your Environment

Verify Local Server Environment

Before we start coding, make sure your local server environment is up and running. You'll need one of the following:

  • XAMPP: Start Apache module from the XAMPP Control Panel
  • MAMP: Start servers from the MAMP application
  • Docker: Make sure your PHP container is running

Note: For this course, we recommend using Docker as mentioned in Module 1, Session 1. However, XAMPP or MAMP are also valid alternatives.

Directory Structure

Create a new file in your web server's document root. The location depends on your setup:

  • XAMPP: C:\xampp\htdocs\ (Windows) or /Applications/XAMPP/htdocs/ (Mac)
  • MAMP: /Applications/MAMP/htdocs/ (Mac) or MAMP installation directory (Windows)
  • Docker: The directory you mapped to your container's web root
Project Directory Structure Document Root my_php_project/ first_script.php Legend: Root Directory Project Folder PHP File

In your project folder, create a new file named first_script.php.

Writing Your First PHP Script

Basic PHP Syntax

Open your first_script.php file in VS Code or your preferred editor. Let's start with the most basic PHP script:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First PHP Script</title>
</head>
<body>
    <h1>Welcome to PHP!</h1>
    
    <?php
    // This is a PHP comment
    echo "<p>Hello, World! This is my first PHP script.</p>";
    ?>
    
    <p>This is regular HTML after the PHP section.</p>
</body>
</html>

Key Elements:

  • <?php - Opening PHP tag that tells the server to start interpreting the code as PHP
  • echo - Command that outputs text (similar to console.log in JavaScript)
  • ?> - Closing PHP tag that tells the server to stop interpreting as PHP

Running Your PHP Script

To run your script:

  1. Save the file
  2. Open your web browser
  3. Navigate to http://localhost/my_php_project/first_script.php

The exact URL may vary depending on your setup. For example:

  • XAMPP/MAMP default: http://localhost/my_php_project/first_script.php
  • MAMP with custom port: http://localhost:8888/my_php_project/first_script.php
  • Docker with custom port: http://localhost:YOUR_PORT/my_php_project/first_script.php

Troubleshooting: If you see the PHP code instead of the executed result, your server isn't processing PHP correctly. Check if your server is running and if the file has a .php extension.

Working with Variables and Data Types

Now let's enhance our script to include variables and different data types. Replace the content of your first_script.php with:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Variables and Data Types</title>
</head>
<body>
    <h1>PHP Variables and Data Types</h1>
    
    <?php
    // String variable
    $name = "John Doe";
    
    // Integer variable
    $age = 30;
    
    // Float variable
    $height = 1.85;
    
    // Boolean variable
    $is_student = true;
    
    // Outputting variables
    echo "<p>Name: $name</p>";
    echo "<p>Age: $age years old</p>";
    echo "<p>Height: $height meters</p>";
    echo "<p>Student: " . ($is_student ? 'Yes' : 'No') . "</p>";
    
    // String concatenation
    echo "<p>" . $name . " is " . $age . " years old.</p>";
    
    // Variable interpolation (works in double quotes)
    echo "<p>$name is $age years old.</p>";
    ?>
</body>
</html>

Key Points about PHP Variables:

  • All variables start with a dollar sign ($)
  • Variable names are case-sensitive ($name and $Name are different variables)
  • PHP is loosely typed - you don't need to declare variable types
  • String concatenation uses the dot (.) operator
  • Variables inside double quotes ("") are evaluated, but not inside single quotes ('')
PHP Data Types PHPDataTypes String: "Text" 'John Doe' Integer: 42 -1 0 Float: 3.14 -2.5 Boolean: true false Array: [1, 2, 3] Object: new StdClass() NULL: null Scalar Types Compound Types Special Type

Implementing Control Structures

Let's expand our script to include conditional statements and loops. Update your first_script.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Control Structures</title>
</head>
<body>
    <h1>PHP Control Structures</h1>
    
    <?php
    // Variables
    $name = "John";
    $age = 20;
    $scores = [85, 92, 78, 96, 88];
    
    // If-else conditional
    echo "<h2>Conditionals</h2>";
    if ($age < 18) {
        echo "<p>$name is a minor.</p>";
    } elseif ($age >= 18 && $age < 65) {
        echo "<p>$name is an adult.</p>";
    } else {
        echo "<p>$name is a senior.</p>";
    }
    
    // Switch statement
    $day = date("l"); // Current day of the week
    echo "<h3>Today is $day</h3>";
    
    switch ($day) {
        case "Monday":
            echo "<p>Start of the work week!</p>";
            break;
        case "Friday":
            echo "<p>End of the work week!</p>";
            break;
        case "Saturday":
        case "Sunday":
            echo "<p>It's the weekend!</p>";
            break;
        default:
            echo "<p>It's a weekday.</p>";
    }
    
    // For loop
    echo "<h2>Loops</h2>";
    echo "<h3>For Loop: Test Scores</h3>";
    echo "<ul>";
    for ($i = 0; $i < count($scores); $i++) {
        echo "<li>Test " . ($i + 1) . ": $scores[$i]</li>";
    }
    echo "</ul>";
    
    // While loop
    echo "<h3>While Loop: Countdown</h3>";
    $countdown = 5;
    echo "<p>";
    while ($countdown > 0) {
        echo "$countdown... ";
        $countdown--;
    }
    echo "Blast off!</p>";
    
    // Foreach loop (best for arrays)
    echo "<h3>Foreach Loop: Test Scores with Grade</h3>";
    echo "<ul>";
    foreach ($scores as $index => $score) {
        // Determine letter grade
        $grade = "";
        if ($score >= 90) {
            $grade = "A";
        } elseif ($score >= 80) {
            $grade = "B";
        } elseif ($score >= 70) {
            $grade = "C";
        } elseif ($score >= 60) {
            $grade = "D";
        } else {
            $grade = "F";
        }
        
        echo "<li>Test " . ($index + 1) . ": $score - Grade: $grade</li>";
    }
    echo "</ul>";
    ?>
</body>
</html>

Key Control Structures in PHP:

  • if, elseif, else: Conditional execution based on expressions
  • switch: Multiple condition testing with more readable syntax
  • for: Loop with initialization, condition, and increment
  • while: Loop that continues as long as the condition is true
  • foreach: Specialized loop for iterating through arrays

Displaying Dynamic Content

One of PHP's strengths is generating dynamic content. Let's create a new file called dynamic_content.php in the same directory:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Dynamic Content</title>
    <style>
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        tr:nth-child(even) { background-color: #f9f9f9; }
    </style>
</head>
<body>
    <h1>PHP Dynamic Content</h1>
    
    <section>
        <h2>Current Date and Time</h2>
        <?php
        // Current date/time
        $current_date = date("F j, Y"); // e.g., April 27, 2025
        $current_time = date("g:i a"); // e.g., 3:45 pm
        
        echo "<p>Today's date: $current_date</p>";
        echo "<p>Current time: $current_time</p>";
        
        // Day of the week and custom greeting
        $day_of_week = date("l");
        $hour = (int)date("G");
        
        $greeting = "";
        if ($hour < 12) {
            $greeting = "Good morning";
        } elseif ($hour < 18) {
            $greeting = "Good afternoon";
        } else {
            $greeting = "Good evening";
        }
        
        echo "<p>$greeting! It's $day_of_week.</p>";
        ?>
    </section>
    
    <section>
        <h2>Server Information</h2>
        <?php
        // Display some server information
        echo "<table>";
        echo "<tr><th>Variable</th><th>Value</th></tr>";
        echo "<tr><td>Server Software</td><td>" . $_SERVER['SERVER_SOFTWARE'] . "</td></tr>";
        echo "<tr><td>Server Name</td><td>" . $_SERVER['SERVER_NAME'] . "</td></tr>";
        echo "<tr><td>Server Protocol</td><td>" . $_SERVER['SERVER_PROTOCOL'] . "</td></tr>";
        echo "<tr><td>Request Method</td><td>" . $_SERVER['REQUEST_METHOD'] . "</td></tr>";
        echo "<tr><td>PHP Version</td><td>" . phpversion() . "</td></tr>";
        echo "</table>";
        ?>
    </section>
    
    <section>
        <h2>Dynamic Content Generation</h2>
        <?php
        // Generate a random quote
        $quotes = [
            "The only way to do great work is to love what you do. - Steve Jobs",
            "Life is what happens when you're busy making other plans. - John Lennon",
            "The future belongs to those who believe in the beauty of their dreams. - Eleanor Roosevelt",
            "Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill",
            "In the middle of difficulty lies opportunity. - Albert Einstein"
        ];
        
        $random_index = array_rand($quotes);
        echo "<blockquote>" . $quotes[$random_index] . "</blockquote>";
        
        // Generate a multiplication table
        $table_size = 5;
        echo "<h3>$table_size x $table_size Multiplication Table</h3>";
        echo "<table>";
        
        // Table header
        echo "<tr><th>x</th>";
        for ($i = 1; $i <= $table_size; $i++) {
            echo "<th>$i</th>";
        }
        echo "</tr>";
        
        // Table body
        for ($row = 1; $row <= $table_size; $row++) {
            echo "<tr>";
            echo "<th>$row</th>";
            
            for ($col = 1; $col <= $table_size; $col++) {
                $result = $row * $col;
                echo "<td>$result</td>";
            }
            
            echo "</tr>";
        }
        echo "</table>";
        ?>
    </section>
</body>
</html>

Key Dynamic Content Features:

  • date() function: Formats the current date and time
  • $_SERVER superglobal: Contains server and environment information
  • phpversion(): Returns the current PHP version
  • array_rand(): Selects a random key from an array
  • Dynamic HTML generation: Creating tables and other content programmatically

Advanced Technique: Processing Form Data

Let's create a simple form processor. Create two new files:

1. contact_form.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Contact Form</title>
    <style>
        form { max-width: 500px; margin: 0 auto; }
        label { display: block; margin-top: 10px; }
        input, textarea { width: 100%; padding: 8px; margin-top: 5px; }
        button { margin-top: 15px; padding: 10px 15px; background-color: #4CAF50; color: white; border: none; cursor: pointer; }
        .error { color: red; }
    </style>
</head>
<body>
    <h1>Contact Form Example</h1>
    
    <?php
    // Initialize variables to avoid undefined variable errors
    $nameErr = $emailErr = $messageErr = "";
    $name = $email = $message = "";
    $formSubmitted = false;
    
    // Check if the form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $formSubmitted = true;
        
        // Validate name
        if (empty($_POST["name"])) {
            $nameErr = "Name is required";
        } else {
            $name = test_input($_POST["name"]);
        }
        
        // Validate email
        if (empty($_POST["email"])) {
            $emailErr = "Email is required";
        } else {
            $email = test_input($_POST["email"]);
            // Check if email is valid
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $emailErr = "Invalid email format";
            }
        }
        
        // Validate message
        if (empty($_POST["message"])) {
            $messageErr = "Message is required";
        } else {
            $message = test_input($_POST["message"]);
        }
    }
    
    // Function to sanitize input data
    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    ?>
    
    <?php if ($formSubmitted && $nameErr == "" && $emailErr == "" && $messageErr == ""): ?>
        <div style="max-width: 500px; margin: 0 auto; padding: 20px; background-color: #dff0d8; border: 1px solid #d6e9c6; color: #3c763d;">
            <h2>Thank You!</h2>
            <p>Your message has been received. Here's a summary of what you submitted:</p>
            <ul>
                <li><strong>Name:</strong> <?php echo $name; ?></li>
                <li><strong>Email:</strong> <?php echo $email; ?></li>
                <li><strong>Message:</strong> <?php echo $message; ?></li>
            </ul>
            <p><a href="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">Submit another message</a></p>
        </div>
    <?php else: ?>
        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
            <div>
                <label for="name">Name:</label>
                <input type="text" id="name" name="name" value="<?php echo $name; ?>">
                <span class="error"><?php echo $nameErr; ?></span>
            </div>
            
            <div>
                <label for="email">Email:</label>
                <input type="text" id="email" name="email" value="<?php echo $email; ?>">
                <span class="error"><?php echo $emailErr; ?></span>
            </div>
            
            <div>
                <label for="message">Message:</label>
                <textarea id="message" name="message" rows="5"><?php echo $message; ?></textarea>
                <span class="error"><?php echo $messageErr; ?></span>
            </div>
            
            <button type="submit">Submit</button>
        </form>
    <?php endif; ?>
</body>
</html>

Key Form Processing Features:

  • $_SERVER["REQUEST_METHOD"]: Checks if the form was submitted via POST
  • $_POST array: Contains data submitted in a POST request
  • form validation: Checking for empty fields and proper formats
  • input sanitization: Cleaning user input to prevent security issues
  • alternative syntax: Using if-endif for templates (preferred in HTML context)

Step 4: Review and Reflect

What We've Learned

Congratulations! You've just created several PHP scripts that demonstrate the fundamentals of PHP programming. Let's review what we've covered:

  • Basic PHP syntax and structure
  • Variables and data types
  • Control structures (conditionals and loops)
  • Generating dynamic content
  • Form processing and validation

Common Mistakes and Troubleshooting

  • Syntax Errors: Missing semicolons, unclosed quotes, or brackets
  • PHP Not Processing: Server not configured properly or file doesn't have .php extension
  • Undefined Variables: Trying to use variables before they're defined
  • Empty Output: Check for error reporting settings or syntax errors

Pro Tip: Enable error reporting during development to catch issues:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
?>

Add this at the top of your PHP files during development (but not in production).

Real-World Applications

PHP is used extensively across the web for various applications:

PHP Applications PHP Applications Content Management Systems E-commerce Platforms Forums & Communities Custom Web Applications WordPress Drupal Joomla Magento WooCommerce PrestaShop phpBB vBulletin CRM Systems Web Portals

WordPress and PHP

WordPress, which powers about 42% of all websites on the internet, is built using PHP. Understanding PHP is crucial for WordPress theme and plugin development, which we'll explore in later modules of this course.

Going Further

Homework Challenge Ideas

  1. Basic: Personal Info Page - Create a PHP script that displays your name, age, favorite hobbies, and skills in a nicely formatted page.
  2. Intermediate: Calculator - Create a simple calculator that can add, subtract, multiply, and divide two numbers input via a form.
  3. Advanced: To-Do List - Create a simple to-do list that stores tasks in a session and allows adding, completing, and removing tasks.

Additional Resources

Conclusion

You've taken your first steps into the world of PHP programming! This server-side language opens up countless possibilities for creating dynamic, interactive websites. As we continue through this course, you'll build upon these fundamentals to create more complex applications, including WordPress themes and plugins.

Remember that PHP, like any programming language, requires practice. Don't be afraid to experiment with the code examples provided and try creating your own PHP scripts to reinforce what you've learned.

Next Up in Module 2: Database integration with MySQL, more advanced PHP concepts, and an introduction to WordPress development.