العربية

← Back to README

Module 7: PHP

Module Overview

This module introduces PHP programming for server-side web development. Students will learn syntax, variables, conditionals, loops, functions, and superglobals by building dynamic web pages.

Prerequisites: Modules 1-6 (HTML, CSS, Bootstrap, JavaScript, AI Tools)

Estimated Duration: 4-5 hours

Tools: XAMPP, VS Code, Browser, phpMyAdmin


Lesson 1: PHP Syntax and Variables

Duration: 40 minutes

Learning Objectives

Instructor Notes

PHP files use the .php extension and must be served through a web server like Apache (via XAMPP). The $ prefix is mandatory for all variables. Students should verify AI-generated PHP code by running it through the browser and checking for parse errors.

Presentation Outline

  1. What is PHP and how it works (5 min)
  2. Basic syntax and tags (10 min)
  3. Variables and data types (10 min)
  4. Output methods (5 min)
  5. Common errors (5 min)

Demonstration

Open XAMPP and start Apache. Create test.php in the htdocs folder. Demonstrate echo, variable interpolation, and concatenation. Show how syntax errors display in the browser.

AI Prompts

  1. "Generate PHP syntax examples with explanations of variable declaration and output methods"
  2. "Create a PHP debugging guide for beginners with common syntax errors and fixes"
  3. "Write a PHP variables practice exercise with starter and final code"

Starter Code

<?php
// TODO: Create variables for your name, age, and city
// TODO: Output a greeting using echo
// TODO: Calculate your birth year (current year - age)
// TODO: Output a sentence using variable interpolation

$name = "John";
$age = 25;
$city = "New York";

echo "Hello, " . $name . "!";
?>

Final Code

<?php
// PHP Syntax and Variables Demo

// Variable declarations
$name = "Alice Johnson";
$age = 22;
$city = "San Francisco";
$isStudent = true;
$gpa = 3.85;

// Output with echo
echo "<h2>Student Profile</h2>";
echo "<p>Name: " . $name . "</p>";

// Output with print
print "<p>Age: $age</p>";

// Variable interpolation in double quotes
echo "<p>City: $city</p>";

// Concatenation
echo "<p>Status: " . ($isStudent ? "Active Student" : "Not a student") . "</p>";

// Calculations
$currentYear = date("Y");
$birthYear = $currentYear - $age;
echo "<p>Birth Year: $birthYear</p>";

// Type demonstration
echo "<h3>Data Types</h3>";
echo "<p>String: $name (type: " . gettype($name) . ")</p>";
echo "<p>Integer: $age (type: " . gettype($age) . ")</p>";
echo "<p>Float: $gpa (type: " . gettype($gpa) . ")</p>";
echo "<p>Boolean: " . ($isStudent ? "true" : "false") . " (type: " . gettype($isStudent) . ")</p>";

// Common syntax error example (commented out)
// $name = "Alice"; // Missing semicolon
// echo $name

// Variable variables (advanced)
$$name = "Variable variable example";
echo "<p>$$name: ${$name}</p>";
?>

Exercises

  1. Create variables for your favorite book (title, author, year). Output them in an HTML sentence.
  2. Calculate the area of a rectangle with width=10 and height=5. Output the result.
  3. Create a boolean variable $hasLicense. Use a ternary operator to output "Can drive" or "Cannot drive".

Homework

  1. Create a PHP page that displays your personal information (name, age, hobbies) using at least 5 variables and HTML formatting.
  2. Research PHP variable naming rules. List 3 valid and 3 invalid variable names with explanations.

Quiz

  1. What symbol must prefix all PHP variables?
    • A) @
    • B) #
    • C) $
    • D) &

    Answer: C

  2. Which statement outputs text in PHP?
    • A) console.log()
    • B) print()
    • C) document.write()
    • D) Both B and C

    Answer: B

  3. What is the file extension for PHP files?
    • A) .html
    • B) .php
    • C) .js
    • D) .ph

    Answer: B

  4. Which character ends every PHP statement?
    • A) .
    • B) ,
    • C) ;
    • D) :

    Answer: C

  5. What does gettype($var) return?
    • A) The value of the variable
    • B) The type of the variable as a string
    • C) The variable name
    • D) true or false

    Answer: B


Lesson 2: Conditionals and Loops

Duration: 45 minutes

Learning Objectives

Instructor Notes

Conditionals control program flow. PHP supports if/else, elseif, switch, and ternary operators. Loops repeat code blocks. Students should verify AI-generated conditions by testing edge cases (empty strings, zero, null).

Presentation Outline

  1. Comparison and logical operators (5 min)
  2. If, else if, else (10 min)
  3. Switch statements (5 min)
  4. Loops: for, while, foreach (15 min)
  5. Break and continue (5 min)

Demonstration

Create conditionals.php. Build a grade calculator using if/else. Create a loop that prints numbers 1-10. Demonstrate foreach with an array.

AI Prompts

  1. "Generate PHP conditional examples with if, else if, switch, and ternary operator"
  2. "Create PHP loop exercises with for, while, and foreach for beginners"
  3. "Write a PHP grade calculator script using conditionals with starter and final code"

Starter Code

<?php
// TODO: Create a variable $score with value 75
// TODO: Use if/else to output grade (A: 90+, B: 80+, C: 70+, D: 60+, F: below 60)
// TODO: Create an array of 3 numbers
// TODO: Use foreach to print each number

$score = 75;

if ($score >= 90) {
    echo "Grade: A";
} elseif ($score >= 80) {
    echo "Grade: B";
}

$numbers = [10, 20, 30];
?>

Final Code

<?php
// Conditionals and Loops Demo

// Score grading system
$score = 85;
echo "<h2>Grade Calculator</h2>";
echo "<p>Score: $score</p>";

if ($score >= 90) {
    echo "<p>Grade: A - Excellent!</p>";
} elseif ($score >= 80) {
    echo "<p>Grade: B - Good job!</p>";
} elseif ($score >= 70) {
    echo "<p>Grade: C - Average</p>";
} elseif ($score >= 60) {
    echo "<p>Grade: D - Passing</p>";
} else {
    echo "<p>Grade: F - Failing</p>";
}

// Ternary operator
$status = ($score >= 60) ? "Passed" : "Failed";
echo "<p>Status: $status</p>";

// Switch statement
$day = date("l");
echo "<h3>Today is $day</h3>";
switch ($day) {
    case "Monday":
        echo "<p>Start of the work week!</p>";
        break;
    case "Friday":
        echo "<p>Almost weekend!</p>";
        break;
    case "Saturday":
    case "Sunday":
        echo "<p>Weekend vibes!</p>";
        break;
    default:
        echo "<p>Regular weekday.</p>";
}

// For loop
echo "<h3>Numbers 1 to 10</h3>";
for ($i = 1; $i <= 10; $i++) {
    echo "<p>$i</p>";
}

// While loop
echo "<h3>Countdown</h3>";
$count = 5;
while ($count > 0) {
    echo "<p>$count</p>";
    $count--;
}
echo "<p>Blast off!</p>";

// Foreach loop
echo "<h3>Fruits List</h3>";
$fruits = ["Apple", "Banana", "Cherry", "Date"];
foreach ($fruits as $index => $fruit) {
    echo "<p>$index: $fruit</p>";
}

// Nested loops - multiplication table
echo "<h3>Multiplication Table (1-5)</h3>";
echo "<table border='1' cellpadding='5' cellspacing='0'>";
for ($i = 1; $i <= 5; $i++) {
    echo "<tr>";
    for ($j = 1; $j <= 5; $j++) {
        echo "<td>" . ($i * $j) . "</td>";
    }
    echo "</tr>";
}
echo "</table>";

// Break and continue
echo "<h3>Numbers 1-10 (skip 5, stop at 8)</h3>";
for ($i = 1; $i <= 10; $i++) {
    if ($i == 5) continue;
    if ($i == 8) break;
    echo "<p>$i</p>";
}
?>

Exercises

  1. Write a PHP script that checks if a number is positive, negative, or zero.
  2. Create a loop that prints only odd numbers from 1 to 20.
  3. Use a foreach loop to calculate the sum of an array of prices.

Homework

  1. Build a PHP number guessing game: the computer picks a random number 1-100, and the user guesses until correct.
  2. Create a PHP script that prints the first 20 Fibonacci numbers using a loop.

Quiz

  1. Which operator checks equality in PHP?
    • A) =
    • B) ==
    • C) ===
    • D) Both B and C

    Answer: D

  2. What does the foreach loop iterate over?
    • A) Numbers
    • B) Arrays and objects
    • C) Strings only
    • D) Conditionals

    Answer: B

  3. Which keyword exits a loop immediately?
    • A) exit
    • B) stop
    • C) break
    • D) return

    Answer: C

  4. What is the output of 3 >= 3?
    • A) true
    • B) false
    • C) 1
    • D) 0

    Answer: A

  5. How do you skip the current iteration and continue to the next one?
    • A) break
    • B) continue
    • C) skip
    • D) next

    Answer: B


Lesson 3: Functions

Duration: 45 minutes

Learning Objectives

Instructor Notes

PHP functions can be declared before or after they are called (unlike JavaScript hoisting, PHP parses the whole file first). The global keyword imports variables from the global scope into functions. Verify AI-generated functions with different input types.

Presentation Outline

  1. Function basics (10 min)
  2. Parameters and return values (10 min)
  3. Default parameters and variable arguments (10 min)
  4. Variable scope (10 min)

Demonstration

Create functions.php. Write a function that calculates tax. Show how to use default parameters and return multiple values as an array.

AI Prompts

  1. "Generate PHP function examples with parameters, return values, and default arguments"
  2. "Create a PHP scope demonstration showing local, global, and static variables"
  3. "Write a PHP utility functions file with string and math helpers"

Starter Code

<?php
// TODO: Create a function greet($name) that returns "Hello, $name!"
// TODO: Create a function add($a, $b) that returns the sum
// TODO: Call both functions and echo the results

function greet($name) {
    return "Hello, " . $name;
}

echo greet("World");
?>

Final Code

<?php
// PHP Functions Demo

// Basic function
function greet($name) {
    return "Hello, $name!";
}

echo "<h2>Functions Demo</h2>";
echo "<p>" . greet("Alice") . "</p>";
echo "<p>" . greet("Bob") . "</p>";

// Function with multiple parameters
function calculateRectangle($width, $height) {
    $area = $width * $height;
    $perimeter = 2 * ($width + $height);
    return [
        'area' => $area,
        'perimeter' => $perimeter
    ];
}

$rect = calculateRectangle(5, 10);
echo "<p>Area: " . $rect['area'] . ", Perimeter: " . $rect['perimeter'] . "</p>";

// Default parameters
function greetWithTitle($name, $title = "Mr./Ms.") {
    return "Good day, $title $name!";
}

echo "<p>" . greetWithTitle("Smith") . "</p>";
echo "<p>" . greetWithTitle("Johnson", "Dr.") . "</p>";

// Variable-length arguments
function sum(...$numbers) {
    return array_sum($numbers);
}

echo "<p>Sum of 1,2,3: " . sum(1, 2, 3) . "</p>";
echo "<p>Sum of 10,20,30,40: " . sum(10, 20, 30, 40) . "</p>";

// Scope demonstration
$globalVar = "I'm global";

function scopeTest() {
    global $globalVar;
    $localVar = "I'm local";
    echo "<p>Inside function: $globalVar, $localVar</p>";
}

scopeTest();
echo "<p>Outside function: $globalVar</p>";
// echo $localVar; // This would cause an error

// Static variable
function counter() {
    static $count = 0;
    $count++;
    return $count;
}

echo "<h3>Static Counter</h3>";
echo "<p>Call 1: " . counter() . "</p>";
echo "<p>Call 2: " . counter() . "</p>";
echo "<p>Call 3: " . counter() . "</p>";

// Recursive function
function factorial($n) {
    if ($n <= 1) return 1;
    return $n * factorial($n - 1);
}

echo "<h3>Factorial</h3>";
echo "<p>5! = " . factorial(5) . "</p>";
echo "<p>7! = " . factorial(7) . "</p>";
?>

Exercises

  1. Write a function isPrime($n) that returns true if a number is prime.
  2. Create a function formatPrice($amount) that formats a number as currency (e.g., "$10.50").
  3. Write a function that takes an array of numbers and returns the largest number.

Homework

  1. Create a PHP file with utility functions: slugify($text) (convert text to URL slug), truncate($text, $length), and formatDate($date).
  2. Research PHP built-in functions for strings (strlen, strpos, substr). Create a summary table.

Quiz

  1. How do you declare a function in PHP?
    • A) function myFunc()
    • B) def myFunc()
    • C) func myFunc()
    • D) create myFunc()

    Answer: A

  2. How do you access a global variable inside a function?
    • A) $globalVar
    • B) global $globalVar
    • C) $GLOBALS['globalVar']
    • D) Both B and C

    Answer: D

  3. What does a function return if no return statement is executed?
    • A) null
    • B) undefined
    • C) 0
    • D) false

    Answer: A

  4. Which keyword allows a variable to retain its value between function calls?
    • A) global
    • B) static
    • C) persistent
    • D) keep

    Answer: B

  5. What does array_sum([1, 2, 3]) return?
    • A) 6
    • B) [1, 2, 3]
    • C) "123"
    • D) 3

    Answer: A


Lesson 4: Superglobals and Form Handling

Duration: 50 minutes

Learning Objectives

Instructor Notes

Superglobals are built-in PHP arrays that are accessible from any scope. $_GET and $_POST collect form data. Students must verify AI-generated form processing code for SQL injection and XSS vulnerabilities. Always validate and sanitize user input.

Presentation Outline

  1. What are superglobals? (5 min)
  2. $_GET and $_POST (15 min)
  3. Form handling workflow (15 min)
  4. Basic validation and sanitization (10 min)

Demonstration

Create a form with name and email fields. Process the submission with PHP. Display the submitted data. Show the difference between GET (URL parameters) and POST (form body).

AI Prompts

  1. "Generate PHP form handling examples using $_POST with validation and error messages"
  2. "Create a PHP superglobals cheat sheet for $_GET, $_POST, $_SESSION, $_SERVER"
  3. "Write a PHP contact form with validation and sanitization starter and final code"

Starter Code

<?php
// process_form.php
// TODO: Check if form was submitted using $_SERVER['REQUEST_METHOD']
// TODO: Retrieve name and email from $_POST
// TODO: Validate that name is not empty
// TODO: Display the submitted data

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $email = $_POST['email'] ?? '';
    echo "Name: $name, Email: $email";
}
?>

<form method="POST">
    <input type="text" name="name" placeholder="Your Name">
    <input type="email" name="email" placeholder="Your Email">
    <button type="submit">Submit</button>
</form>

Final Code

<?php
// form_handler.php
$name = $email = $message = "";
$nameError = $emailError = $messageError = "";
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate name
    if (empty($_POST['name'])) {
        $nameError = "Name is required";
    } else {
        $name = htmlspecialchars(trim($_POST['name']));
        if (strlen($name) < 2) {
            $nameError = "Name must be at least 2 characters";
        }
    }

    // Validate email
    if (empty($_POST['email'])) {
        $emailError = "Email is required";
    } else {
        $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailError = "Invalid email format";
        }
    }

    // Validate message
    if (empty($_POST['message'])) {
        $messageError = "Message is required";
    } else {
        $message = htmlspecialchars(trim($_POST['message']));
    }

    // If no errors, process the form
    if (empty($nameError) && empty($emailError) && empty($messageError)) {
        $success = true;
        // In production, you would save to database or send email here
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Form</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 500px; margin: 2rem auto; padding: 0 1rem; }
        .error { color: #d32f2f; font-size: 0.9rem; }
        .success { color: #388e3c; padding: 10px; background: #e8f5e9; border-radius: 5px; }
        input, textarea { width: 100%; padding: 8px; margin: 5px 0; box-sizing: border-box; }
        button { padding: 10px 20px; background: #1976d2; color: white; border: none; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Contact Form</h1>

    <?php if ($success): ?>
        <div class="success">
            <h3>Message Sent!</h3>
            <p>Name: <?php echo $name; ?></p>
            <p>Email: <?php echo $email; ?></p>
            <p>Message: <?php echo $message; ?></p>
        </div>
    <?php else: ?>
        <form method="POST">
            <div>
                <label>Name:</label>
                <input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>">
                <?php if ($nameError): ?>
                    <span class="error"><?php echo $nameError; ?></span>
                <?php endif; ?>
            </div>
            <div>
                <label>Email:</label>
                <input type="email" name="email" value="<?php echo htmlspecialchars($email); ?>">
                <?php if ($emailError): ?>
                    <span class="error"><?php echo $emailError; ?></span>
                <?php endif; ?>
            </div>
            <div>
                <label>Message:</label>
                <textarea name="message" rows="4"><?php echo htmlspecialchars($message); ?></textarea>
                <?php if ($messageError): ?>
                    <span class="error"><?php echo $messageError; ?></span>
                <?php endif; ?>
            </div>
            <button type="submit">Send Message</button>
        </form>
    <?php endif; ?>

    <h3>Server Info</h3>
    <p>PHP Version: <?php echo phpversion(); ?></p>
    <p>Server Software: <?php echo $_SERVER['SERVER_SOFTWARE'] ?? 'N/A'; ?></p>
    <p>Request Method: <?php echo $_SERVER['REQUEST_METHOD'] ?? 'N/A'; ?></p>
</body>
</html>

Exercises

  1. Create a simple form with a username field. Use PHP to check if the username is longer than 3 characters.
  2. Modify the final code to add a phone number field with validation (digits only, 10-15 characters).
  3. Use $_GET to create a search URL like search.php?q=php and display the search query.

Homework

  1. Build a registration form with name, email, password, and confirm password fields. Validate all fields and check if passwords match.
  2. Research PHP filter functions (filter_var, FILTER_SANITIZE_*, FILTER_VALIDATE_*). Create a summary table.

Quiz

  1. Which superglobal contains form data sent with POST?
    • A) $_GET
    • B) $_POST
    • C) $_FORM
    • D) $_DATA

    Answer: B

  2. What does htmlspecialchars() do?
    • A) Encodes special HTML characters
    • B) Removes all HTML tags
    • C) Validates email addresses
    • D) Encrypts data

    Answer: A

  3. Which method is used to check the request method in PHP?
    • A) $_SERVER['REQUEST_METHOD']
    • B) $_POST['method']
    • C) getRequestMethod()
    • D) request()->method()

    Answer: A

  4. What does filter_var($email, FILTER_VALIDATE_EMAIL) return if valid?
    • A) true
    • B) The sanitized email
    • C) The email string
    • D) 1

    Answer: C

  5. Which superglobal contains information about headers, paths, and script locations?
    • A) $_GET
    • B) $_POST
    • C) $_SESSION
    • D) $_SERVER

    Answer: D


Lesson 5: Advanced PHP Concepts and Mini Project

Duration: 60 minutes

Learning Objectives

Instructor Notes

include and require import files. require causes a fatal error if the file is missing; include only raises a warning. Students should verify AI-generated includes/requires by testing missing file scenarios. Use associative arrays for database-like data structures.

Presentation Outline

  1. Include and require (10 min)
  2. Associative arrays (10 min)
  3. Error handling basics (10 min)
  4. Mini project: Contact list (25 min)

Demonstration

Create a mini project with header.php, footer.php, and index.php using include. Build a simple contact list using associative arrays and display it in an HTML table.

AI Prompts

  1. "Generate PHP include and require examples with error handling explanations"
  2. "Create a PHP contact list mini project using associative arrays and HTML output"
  3. "Write PHP debugging exercises for common errors: undefined variable, missing file, syntax error"

Starter Code

<?php
// index.php
// TODO: Include header.php and footer.php
// TODO: Create an associative array of 3 contacts (name, email, phone)
// TODO: Display contacts in an HTML table

require 'header.php';

$contacts = [
    ['name' => 'Alice', 'email' => 'alice@example.com', 'phone' => '555-0101'],
];

echo "<table>";
foreach ($contacts as $contact) {
    echo "<tr><td>" . $contact['name'] . "</td></tr>";
}
echo "</table>";

require 'footer.php';
?>

Final Code

<?php
// config.php - Configuration file
define('SITE_NAME', 'Contact Manager');
define('SITE_URL', 'http://localhost/contacts');
?>

<?php
// header.php
require_once 'config.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo SITE_NAME; ?></title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
        th { background-color: #1976d2; color: white; }
        tr:nth-child(even) { background-color: #f2f2f2; }
        .actions a { margin-right: 10px; text-decoration: none; padding: 5px 10px; border-radius: 3px; }
        .edit { background: #ff9800; color: white; }
        .delete { background: #f44336; color: white; }
    </style>
</head>
<body>
    <h1><?php echo SITE_NAME; ?></h1>
    <nav>
        <a href="index.php">Home</a> |
        <a href="add.php">Add Contact</a>
    </nav>
    <hr>
<?php
// index.php
require_once 'header.php';

// Contact data (simulating database)
$contacts = [
    ['id' => 1, 'name' => 'Alice Johnson', 'email' => 'alice@example.com', 'phone' => '555-0101', 'category' => 'Friend'],
    ['id' => 2, 'name' => 'Bob Smith', 'email' => 'bob@example.com', 'phone' => '555-0102', 'category' => 'Work'],
    ['id' => 3, 'name' => 'Carol White', 'email' => 'carol@example.com', 'phone' => '555-0103', 'category' => 'Family'],
    ['id' => 4, 'name' => 'David Brown', 'email' => 'david@example.com', 'phone' => '555-0104', 'category' => 'Friend'],
];

// Search functionality
$search = '';
$filteredContacts = $contacts;
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = htmlspecialchars(trim($_GET['search']));
    $filteredContacts = array_filter($contacts, function($contact) use ($search) {
        return stripos($contact['name'], $search) !== false ||
               stripos($contact['email'], $search) !== false;
    });
}
?>

<h2>Contact List</h2>

<!-- Search form -->
<form method="GET" action="index.php">
    <input type="text" name="search" placeholder="Search contacts..." value="<?php echo htmlspecialchars($search); ?>">
    <button type="submit">Search</button>
    <?php if ($search): ?>
        <a href="index.php">Clear</a>
    <?php endif; ?>
</form>

<!-- Results count -->
<p><?php echo count($filteredContacts); ?> contact(s) found</p>

<!-- Contacts table -->
<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Category</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($filteredContacts as $contact): ?>
        <tr>
            <td><?php echo $contact['id']; ?></td>
            <td><?php echo htmlspecialchars($contact['name']); ?></td>
            <td><?php echo htmlspecialchars($contact['email']); ?></td>
            <td><?php echo htmlspecialchars($contact['phone']); ?></td>
            <td><?php echo htmlspecialchars($contact['category']); ?></td>
            <td class="actions">
                <a href="edit.php?id=<?php echo $contact['id']; ?>" class="edit">Edit</a>
                <a href="delete.php?id=<?php echo $contact['id']; ?>" class="delete" onclick="return confirm('Are you sure?')">Delete</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<?php require_once 'footer.php'; ?>
<?php
// footer.php
?>
    <hr>
    <footer>
        <p>Contact Manager v1.0 | Built with PHP</p>
    </footer>
</body>
</html>
<?php
// add.php - Add new contact
require_once 'header.php';

$name = $email = $phone = $category = '';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = htmlspecialchars(trim($_POST['name'] ?? ''));
    $email = htmlspecialchars(trim($_POST['email'] ?? ''));
    $phone = htmlspecialchars(trim($_POST['phone'] ?? ''));
    $category = htmlspecialchars(trim($_POST['category'] ?? ''));

    if (empty($name)) $errors[] = "Name is required";
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email is required";
    if (empty($phone)) $errors[] = "Phone is required";

    if (empty($errors)) {
        echo "<div class='success'>Contact added successfully! (In production, save to database)</div>";
        // Redirect back to index
        header("Location: index.php");
        exit();
    }
}
?>

<h2>Add New Contact</h2>

<?php foreach ($errors as $error): ?>
    <p class="error"><?php echo $error; ?></p>
<?php endforeach; ?>

<form method="POST">
    <div>
        <label>Name:</label>
        <input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>">
    </div>
    <div>
        <label>Email:</label>
        <input type="email" name="email" value="<?php echo htmlspecialchars($email); ?>">
    </div>
    <div>
        <label>Phone:</label>
        <input type="text" name="phone" value="<?php echo htmlspecialchars($phone); ?>">
    </div>
    <div>
        <label>Category:</label>
        <select name="category">
            <option value="">Select category</option>
            <option value="Friend" <?php echo $category === 'Friend' ? 'selected' : ''; ?>>Friend</option>
            <option value="Work" <?php echo $category === 'Work' ? 'selected' : ''; ?>>Work</option>
            <option value="Family" <?php echo $category === 'Family' ? 'selected' : ''; ?>>Family</option>
        </select>
    </div>
    <button type="submit">Add Contact</button>
    <a href="index.php">Cancel</a>
</form>

<?php require_once 'footer.php'; ?>

Exercises

  1. Modify the contact list to display only contacts in a selected category using a dropdown filter.
  2. Add pagination to the contact list (show 2 contacts per page).
  3. Create a statistics page that counts contacts by category.

Homework

  1. Expand the contact manager to allow editing and deleting contacts (use arrays to simulate database).
  2. Research PHP include, include_once, require, and require_once. Create a comparison table explaining when to use each.

Quiz

  1. What is the difference between include and require?
    • A) No difference
    • B) include gives warning, require gives fatal error on failure
    • C) require gives warning, include gives fatal error
    • D) include is for HTML, require is for PHP

    Answer: B

  2. Which function checks if a file exists before including it?
    • A) file_exists()
    • B) include_exists()
    • C) check_file()
    • D) is_file()

    Answer: A

  3. How do you define a constant in PHP?
    • A) $CONSTANT = value
    • B) const CONSTANT = value
    • C) define('CONSTANT', value)
    • D) Both B and C

    Answer: D

  4. What does array_filter() do?
    • A) Removes duplicate values
    • B) Filters elements using a callback function
    • C) Sorts an array
    • D) Merges arrays

    Answer: B

  5. Which function redirects to another page?
    • A) header("Location: page.php")
    • B) redirect("page.php")
    • C) go_to("page.php")
    • D) location("page.php")

    Answer: A