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
- Write basic PHP syntax inside HTML
- Declare variables with
$ prefix
- Output data with
echo and print
- Use common data types (string, integer, float, boolean)
- Debug syntax errors
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
- What is PHP and how it works (5 min)
- Basic syntax and tags (10 min)
- Variables and data types (10 min)
- Output methods (5 min)
- 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
- "Generate PHP syntax examples with explanations of variable declaration and output methods"
- "Create a PHP debugging guide for beginners with common syntax errors and fixes"
- "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
- Create variables for your favorite book (title, author, year). Output them in an HTML sentence.
- Calculate the area of a rectangle with width=10 and height=5. Output the result.
- Create a boolean variable
$hasLicense. Use a ternary operator to output "Can drive" or "Cannot drive".
Homework
- Create a PHP page that displays your personal information (name, age, hobbies) using at least 5 variables and HTML formatting.
- Research PHP variable naming rules. List 3 valid and 3 invalid variable names with explanations.
Quiz
- What symbol must prefix all PHP variables?
Answer: C
- Which statement outputs text in PHP?
- A) console.log()
- B) print()
- C) document.write()
- D) Both B and C
Answer: B
- What is the file extension for PHP files?
- A) .html
- B) .php
- C) .js
- D) .ph
Answer: B
- Which character ends every PHP statement?
Answer: C
- 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
- Use if, else if, and else statements
- Apply switch statements for multiple conditions
- Write for, while, and foreach loops
- Use comparison and logical operators
- Control program flow based on conditions
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
- Comparison and logical operators (5 min)
- If, else if, else (10 min)
- Switch statements (5 min)
- Loops: for, while, foreach (15 min)
- 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
- "Generate PHP conditional examples with if, else if, switch, and ternary operator"
- "Create PHP loop exercises with for, while, and foreach for beginners"
- "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
- Write a PHP script that checks if a number is positive, negative, or zero.
- Create a loop that prints only odd numbers from 1 to 20.
- Use a
foreach loop to calculate the sum of an array of prices.
Homework
- Build a PHP number guessing game: the computer picks a random number 1-100, and the user guesses until correct.
- Create a PHP script that prints the first 20 Fibonacci numbers using a loop.
Quiz
- Which operator checks equality in PHP?
- A) =
- B) ==
- C) ===
- D) Both B and C
Answer: D
- What does the
foreach loop iterate over?
- A) Numbers
- B) Arrays and objects
- C) Strings only
- D) Conditionals
Answer: B
- Which keyword exits a loop immediately?
- A) exit
- B) stop
- C) break
- D) return
Answer: C
- What is the output of
3 >= 3?
- A) true
- B) false
- C) 1
- D) 0
Answer: A
- 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
- Declare and call functions in PHP
- Pass parameters and return values
- Use default and variable-length argument lists
- Understand variable scope in PHP functions
- Write reusable code
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
- Function basics (10 min)
- Parameters and return values (10 min)
- Default parameters and variable arguments (10 min)
- 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
- "Generate PHP function examples with parameters, return values, and default arguments"
- "Create a PHP scope demonstration showing local, global, and static variables"
- "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
- Write a function
isPrime($n) that returns true if a number is prime.
- Create a function
formatPrice($amount) that formats a number as currency (e.g., "$10.50").
- Write a function that takes an array of numbers and returns the largest number.
Homework
- Create a PHP file with utility functions:
slugify($text) (convert text to URL slug), truncate($text, $length), and formatDate($date).
- Research PHP built-in functions for strings (strlen, strpos, substr). Create a summary table.
Quiz
- How do you declare a function in PHP?
- A) function myFunc()
- B) def myFunc()
- C) func myFunc()
- D) create myFunc()
Answer: A
- 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
- What does a function return if no return statement is executed?
- A) null
- B) undefined
- C) 0
- D) false
Answer: A
- Which keyword allows a variable to retain its value between function calls?
- A) global
- B) static
- C) persistent
- D) keep
Answer: B
- 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
- Understand PHP superglobal arrays ($_GET, $_POST, $_SESSION, $_SERVER)
- Process HTML form data in PHP
- Validate user input
- Use $_GET and $_POST for data retrieval
- Understand basic security concepts
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
- What are superglobals? (5 min)
- $_GET and $_POST (15 min)
- Form handling workflow (15 min)
- 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
- "Generate PHP form handling examples using $_POST with validation and error messages"
- "Create a PHP superglobals cheat sheet for $_GET, $_POST, $_SESSION, $_SERVER"
- "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
- Create a simple form with a username field. Use PHP to check if the username is longer than 3 characters.
- Modify the final code to add a phone number field with validation (digits only, 10-15 characters).
- Use
$_GET to create a search URL like search.php?q=php and display the search query.
Homework
- Build a registration form with name, email, password, and confirm password fields. Validate all fields and check if passwords match.
- Research PHP filter functions (
filter_var, FILTER_SANITIZE_*, FILTER_VALIDATE_*). Create a summary table.
Quiz
- Which superglobal contains form data sent with POST?
- A) $_GET
- B) $_POST
- C) $_FORM
- D) $_DATA
Answer: B
- What does
htmlspecialchars() do?
- A) Encodes special HTML characters
- B) Removes all HTML tags
- C) Validates email addresses
- D) Encrypts data
Answer: A
- 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
- 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
- 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
- Use include and require for code reusability
- Understand the difference between include and require
- Work with associative arrays
- Build a simple PHP mini project
- Debug PHP errors effectively
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
- Include and require (10 min)
- Associative arrays (10 min)
- Error handling basics (10 min)
- 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
- "Generate PHP include and require examples with error handling explanations"
- "Create a PHP contact list mini project using associative arrays and HTML output"
- "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
- Modify the contact list to display only contacts in a selected category using a dropdown filter.
- Add pagination to the contact list (show 2 contacts per page).
- Create a statistics page that counts contacts by category.
Homework
- Expand the contact manager to allow editing and deleting contacts (use arrays to simulate database).
- Research PHP
include, include_once, require, and require_once. Create a comparison table explaining when to use each.
Quiz
- 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
- Which function checks if a file exists before including it?
- A) file_exists()
- B) include_exists()
- C) check_file()
- D) is_file()
Answer: A
- 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
- 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
- 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
الوحدة 7: PHP
نظرة عامة على الوحدة
تُقدّم هذه الوحدة لغة PHP للبرمجة من جهة الخادم (server-side). سيتعلم الطلاب الصيغة (syntax) والمتغيرات والشرطيات والحلقات والدوال والمتغيرات الفائقة (superglobals) من خلال بناء صفحات ويب ديناميكية.
المتطلبات الأساسية: الوحدات 1-6 (HTML، CSS، Bootstrap، JavaScript، أدوات الذكاء الاصطناعي)
المدة التقديرية: 4-5 ساعات
الأدوات: XAMPP، VS Code، المتصفح، phpMyAdmin
الدرس 1: صيغة PHP والمتغيرات
المدة: 40 دقيقة
أهداف التعلم
- كتابة صيغة PHP أساسية داخل HTML
- تعريف المتغيرات باستخدام البادئة
$
- إخراج البيانات باستخدام
echo و print
- استخدام أنواع البيانات الشائعة (نص، عدد صحيح، عشري، منطقي)
- تصحيح أخطاء الصيغة
ملاحظات للمدرّس
تستخدم ملفات PHP الامتداد .php ويجب تقديمها عبر خادم ويب مثل Apache (من خلال XAMPP). البادئة $ إلزامية لكل المتغيرات. يجب على الطلاب التحقق من أكواد PHP التي يولّدها الذكاء الاصطناعي بتشغيلها في المتصفح والتأكد من عدم وجود أخطاء تحليل (parse errors).
خطة العرض
- ما هي PHP وكيف تعمل (5 دقائق)
- الصيغة الأساسية والوسوم (10 دقائق)
- المتغيرات وأنواع البيانات (10 دقائق)
- طرق الإخراج (5 دقائق)
- الأخطاء الشائعة (5 دقائق)
العرض العملي
افتح XAMPP وشغّل Apache. أنشئ ملف test.php داخل مجلد htdocs. اعرض echo واستيفاء المتغيرات (interpolation) والدمج (concatenation). أظهر كيف تظهر أخطاء الصيغة في المتصفح.
أوامر الذكاء الاصطناعي
- "Generate PHP syntax examples with explanations of variable declaration and output methods"
- "Create a PHP debugging guide for beginners with common syntax errors and fixes"
- "Write a PHP variables practice exercise with starter and final 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 . "!";
?>
الكود النهائي
<?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>";
?>
تمارين
- أنشئ متغيرات لكتابك المفضل (العنوان، المؤلف، السنة). أخرجها في جملة HTML.
- احسب مساحة مستطيل بعرض 10 وارتفاع 5. أخرج النتيجة.
- أنشئ متغيرًا منطقيًا
$hasLicense. استخدم العامل الثلاثي (ternary) لإخراج "Can drive" أو "Cannot drive".
الواجب المنزلي
- أنشئ صفحة PHP تعرض معلوماتك الشخصية (الاسم، العمر، الهوايات) باستخدام 5 متغيرات على الأقل وتنسيق HTML.
- ابحث عن قواعد تسمية المتغيرات في PHP. اذكر 3 أسماء صحيحة و3 أسماء غير صحيحة مع الشرح.
الاختبار القصير
- ما الرمز الذي يجب أن يسبق جميع متغيرات PHP؟
الإجابة: C
- أي عبارة تُخرج نصًا في PHP؟
- A) console.log()
- B) print()
- C) document.write()
- D) كلاهما B و C
الإجابة: B
- ما امتداد ملفات PHP؟
- A) .html
- B) .php
- C) .js
- D) .ph
الإجابة: B
- أي رمز ينهي كل عبارة في PHP؟
الإجابة: C
- ماذا يُرجع
gettype($var)؟
- A) قيمة المتغير
- B) نوع المتغير كنص
- C) اسم المتغير
- D) صحيح أو خطأ
الإجابة: B
الدرس 2: الشرطيات والحلقات
المدة: 45 دقيقة
أهداف التعلم
- استخدام الجمل if و else if و else
- تطبيق جمل switch لشروط متعددة
- كتابة الحلقات for و while و foreach
- استخدام عوامل المقارنة والعوامل المنطقية
- التحكم في تدفق البرنامج بناءً على الشروط
ملاحظات للمدرّس
تتحكم الشرطيات في تدفق البرنامج. تدعم PHP الجمل if/else و elseif و switch والعامل الثلاثي. وتُكرّر الحلقات كتل الأكواد. يجب على الطلاب التحقق من الشروط التي يولّدها الذكاء الاصطناعي باختبار الحالات الحدية (نصوص فارغة، صفر، قيمة فارغة).
خطة العرض
- عوامل المقارنة والعوامل المنطقية (5 دقائق)
- if و else if و else (10 دقائق)
- جمل switch (5 دقائق)
- الحلقات: for و while و foreach (15 دقيقة)
- break و continue (5 دقائق)
العرض العملي
أنشئ ملف conditionals.php. ابنِ حاسبة درجات باستخدام if/else. أنشئ حلقة تطبع الأرقام من 1 إلى 10. اعرض foreach مع مصفوفة.
أوامر الذكاء الاصطناعي
- "Generate PHP conditional examples with if, else if, switch, and ternary operator"
- "Create PHP loop exercises with for, while, and foreach for beginners"
- "Write a PHP grade calculator script using conditionals with starter and final 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];
?>
الكود النهائي
<?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>";
}
?>
تمارين
- اكتب سكربت PHP يتحقق مما إذا كان الرقم موجبًا أو سالبًا أو صفرًا.
- أنشئ حلقة تطبع الأرقام الفردية فقط من 1 إلى 20.
- استخدم حلقة
foreach لحساب مجموع مصفوفة من الأسعار.
الواجب المنزلي
- ابنِ لعبة تخمين أرقام في PHP: يختار الحاسوب رقمًا عشوائيًا من 1 إلى 100، ويخمّن المستخدم حتى يصيب.
- أنشئ سكربت PHP يطبع أول 20 عددًا من متتالية فيبوناتشي باستخدام حلقة.
الاختبار القصير
- أي عامل يتحقق من التساوي في PHP؟
- A) =
- B) ==
- C) ===
- D) كلاهما B و C
الإجابة: D
- على ماذا تكرر حلقة
foreach؟
- A) الأرقام
- B) المصفوفات والكائنات
- C) النصوص فقط
- D) الشروط
الإجابة: B
- أي كلمة مفتاحية تخرج من الحلقة فورًا؟
- A) exit
- B) stop
- C) break
- D) return
الإجابة: C
- ما ناتج
3 >= 3؟
- A) true
- B) false
- C) 1
- D) 0
الإجابة: A
- كيف تتخطى التكرار الحالي وتنتقل إلى التالي؟
- A) break
- B) continue
- C) skip
- D) next
الإجابة: B
الدرس 3: الدوال (Functions)
المدة: 45 دقيقة
أهداف التعلم
- تعريف واستدعاء الدوال في PHP
- تمرير المعاملات وإرجاع القيم
- استخدام المعاملات الافتراضية وقوائم المعاملات متغيرة الطول
- فهم نطاق المتغيرات في دوال PHP
- كتابة كود قابل لإعادة الاستخدام
ملاحظات للمدرّس
يمكن تعريف دوال PHP قبل أو بعد استدعائها (على عكس JavaScript، تحلل PHP الملف كاملًا أولًا). تستورد الكلمة المفتاحية global المتغيرات من النطاق العام إلى داخل الدوال. تحقق من الدوال التي يولّدها الذكاء الاصطناعي بأنواع مدخلات مختلفة.
خطة العرض
- أساسيات الدوال (10 دقائق)
- المعاملات والقيم المرجعة (10 دقائق)
- المعاملات الافتراضية والمعاملات المتغيرة (10 دقائق)
- نطاق المتغيرات (10 دقائق)
العرض العملي
أنشئ ملف functions.php. اكتب دالة تحسب الضريبة. أظهر كيفية استخدام المعاملات الافتراضية وإرجاع قيم متعددة كمصفوفة.
أوامر الذكاء الاصطناعي
- "Generate PHP function examples with parameters, return values, and default arguments"
- "Create a PHP scope demonstration showing local, global, and static variables"
- "Write a PHP utility functions file with string and math helpers"
الكود الابتدائي
<?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");
?>
الكود النهائي
<?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>";
?>
تمارين
- اكتب دالة
isPrime($n) تُرجع true إذا كان الرقم أوليًا.
- أنشئ دالة
formatPrice($amount) تنسّق الرقم كعملة (مثل "$10.50").
- اكتب دالة تأخذ مصفوفة أرقام وتُرجع أكبر رقم.
الواجب المنزلي
- أنشئ ملف PHP فيه دوال مساعدة:
slugify($text) (تحويل النص إلى رابط)، truncate($text, $length)، و formatDate($date).
- ابحث عن دوال PHP المدمجة للنصوص (strlen، strpos، substr). أنشئ جدولًا ملخصًا.
الاختبار القصير
- كيف تعرّف دالة في PHP؟
- A) function myFunc()
- B) def myFunc()
- C) func myFunc()
- D) create myFunc()
الإجابة: A
- كيف تصل إلى متغير عام داخل دالة؟
- A) $globalVar
- B) global $globalVar
- C) $GLOBALS['globalVar']
- D) كلاهما B و C
الإجابة: D
- ماذا تُرجع الدالة إذا لم يُنفّذ أي عبارة return؟
- A) null
- B) undefined
- C) 0
- D) false
الإجابة: A
- أي كلمة مفتاحية تسمح للمتغير بالاحتفاظ بقيمته بين استدعاءات الدالة؟
- A) global
- B) static
- C) persistent
- D) keep
الإجابة: B
- ماذا يُرجع
array_sum([1, 2, 3])؟
- A) 6
- B) [1, 2, 3]
- C) "123"
- D) 3
الإجابة: A
الدرس 4: المتغيرات الفائقة ومعالجة النماذج
المدة: 50 دقيقة
أهداف التعلم
- فهم مصفوفات المتغيرات الفائقة في PHP ($_GET، $_POST، $_SESSION، $_SERVER)
- معالجة بيانات نماذج HTML في PHP
- التحقق من مدخلات المستخدم
- استخدام $_GET و $_POST لاسترجاع البيانات
- فهم مفاهيم الأمان الأساسية
ملاحظات للمدرّس
المتغيرات الفائقة هي مصفوفات مدمجة في PHP يمكن الوصول إليها من أي نطاق. تجمع $_GET و $_POST بيانات النموذج. يجب على الطلاب التحقق من أكواد معالجة النماذج التي يولّدها الذكاء الاصطناعي من ثغرات حقن SQL و XSS. تحقق دائمًا من مدخلات المستخدم نظّفها.
خطة العرض
- ما هي المتغيرات الفائقة؟ (5 دقائق)
- $_GET و $_POST (15 دقيقة)
- سير عمل معالجة النماذج (15 دقيقة)
- التحقق والتنظيف الأساسي (10 دقائق)
العرض العملي
أنشئ نموذجًا بحقلي الاسم والبريد الإلكتروني. عالج الإرسال باستخدام PHP. اعرض البيانات المرسلة. أوضح الفرق بين GET (معاملات الرابط) و POST (جسم النموذج).
أوامر الذكاء الاصطناعي
- "Generate PHP form handling examples using $_POST with validation and error messages"
- "Create a PHP superglobals cheat sheet for $_GET, $_POST, $_SESSION, $_SERVER"
- "Write a PHP contact form with validation and sanitization starter and final 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>
الكود النهائي
<?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>
تمارين
- أنشئ نموذجًا بسيطًا بحقل اسم المستخدم. استخدم PHP للتحقق مما إذا كان الاسم أطول من 3 أحرف.
- عدّل الكود النهائي لإضافة حقل رقم هاتف مع تحقق (أرقام فقط، 10-15 حرفًا).
- استخدم
$_GET لإنشاء رابط بحث مثل search.php?q=php واعرض عبارة البحث.
الواجب المنزلي
- ابنِ نموذج تسجيل بحقول الاسم والبريد الإلكتروني وكلمة المرور وتأكيد كلمة المرور. تحقق من كل الحقول وتأكد من تطابق كلمتي المرور.
- ابحث عن دوال التصفية في PHP (
filter_var، FILTER_SANITIZE_*، FILTER_VALIDATE_*). أنشئ جدولًا ملخصًا.
الاختبار القصير
- أي متغير فائق يحتوي بيانات النموذج المرسلة بـ POST؟
- A) $_GET
- B) $_POST
- C) $_FORM
- D) $_DATA
الإجابة: B
- ماذا تفعل
htmlspecialchars()؟
- A) ترمّز رموز HTML الخاصة
- B) تزيل كل وسوم HTML
- C) تتحقق من عناوين البريد
- D) تشفّر البيانات
الإجابة: A
- ما الطريقة المستخدمة للتحقق من طريقة الطلب في PHP؟
- A) $_SERVER['REQUEST_METHOD']
- B) $_POST['method']
- C) getRequestMethod()
- D) request()->method()
الإجابة: A
- ماذا يُرجع
filter_var($email, FILTER_VALIDATE_EMAIL) إذا كان صحيحًا؟
- A) true
- B) البريد المرشّح
- C) نص البريد
- D) 1
الإجابة: C
- أي متغير فائق يحتوي معلومات عن الترويسات والمسارات ومواقع السكربت؟
- A) $_GET
- B) $_POST
- C) $_SESSION
- D) $_SERVER
الإجابة: D
الدرس 5: مفاهيم PHP المتقدمة ومشروع صغير
المدة: 60 دقيقة
أهداف التعلم
- استخدام include و require لإعادة استخدام الكود
- فهم الفرق بين include و require
- العمل مع المصفوفات الترابطية
- بناء مشروع PHP صغير
- تصحيح أخطاء PHP بفعالية
ملاحظات للمدرّس
تستورد include و require الملفات. تسبب require خطأً فادحًا إذا كان الملف مفقودًا؛ بينما تُطلق include تحذيرًا فقط. يجب على الطلاب التحقق من أكواد الاستيراد التي يولّدها الذكاء الاصطناعي باختبار سيناريوهات فقدان الملف. استخدم المصفوفات الترابطية لهياكل تشبه قواعد البيانات.
خطة العرض
- include و require (10 دقائق)
- المصفوفات الترابطية (10 دقائق)
- أساسيات معالجة الأخطاء (10 دقائق)
- مشروع صغير: قائمة جهات اتصال (25 دقيقة)
العرض العملي
أنشئ مشروعًا صغيرًا بملفات header.php و footer.php و index.php باستخدام include. ابنِ قائمة جهات اتصال بسيطة باستخدام المصفوفات الترابطية واعرضها في جدول HTML.
أوامر الذكاء الاصطناعي
- "Generate PHP include and require examples with error handling explanations"
- "Create a PHP contact list mini project using associative arrays and HTML output"
- "Write PHP debugging exercises for common errors: undefined variable, missing file, syntax error"
الكود الابتدائي
<?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';
?>
الكود النهائي
<?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'; ?>
تمارين
- عدّل قائمة جهات الاتصال لعرض الجهات في فئة مختارة فقط باستخدام مرشح قائمة منسدلة.
- أضف ترقيم صفحات لقائمة جهات الاتصال (اعرض جهتين في كل صفحة).
- أنشئ صفحة إحصائيات تحسب عدد جهات الاتصال حسب الفئة.
الواجب المنزلي
- وسّع مدير جهات الاتصال للسماح بتعديل وحذف الجهات (استخدم المصفوفات لمحاكاة قاعدة البيانات).
- ابحث عن
include و include_once و require و require_once في PHP. أنشئ جدول مقارنة يوضح متى تُستخدم كل منها.
الاختبار القصير
- ما الفرق بين
include و require؟
- A) لا فرق
- B) include تعطي تحذيرًا، require تعطي خطأً فادحًا عند الفشل
- C) require تعطي تحذيرًا، include تعطي خطأً فادحًا
- D) include لـ HTML و require لـ PHP
الإجابة: B
- أي دالة تتحقق من وجود الملف قبل استيراده؟
- A) file_exists()
- B) include_exists()
- C) check_file()
- D) is_file()
الإجابة: A
- كيف تعرّف ثابتًا في PHP؟
- A) $CONSTANT = value
- B) const CONSTANT = value
- C) define('CONSTANT', value)
- D) كلاهما B و C
الإجابة: D
- ماذا تفعل
array_filter()؟
- A) تزيل القيم المكررة
- B) تُرشّح العناصر باستخدام دالة استدعاء
- C) ترتّب المصفوفة
- D) تدمج المصفوفات
الإجابة: B
- أي دالة تعيد التوجيه إلى صفحة أخرى؟
- A) header("Location: page.php")
- B) redirect("page.php")
- C) go_to("page.php")
- D) location("page.php")
الإجابة: A