Certainly! Below is a set of PHP practical exercises designed to cover the full course content outlined in your syllabus. Each exercise includes a description, syllabus coverage, aim, and PHP code. These exercises are structured to align with the Competency 10: Develops websites incorporating multimedia technologies (using HTML 5) and Competency 10.7: Creates dynamic web pages using PHP and MySQL
Exercise 10.1: Basic PHP Syntax
Description : Write a PHP script that outputs “Hello, World!” on a web page.
Syllabus Coverage : Introduction to dynamic web pages, embedding PHP code into web pages.
Aim : Introduce students to basic PHP syntax and its integration with HTML.
1 2 3 4 5 6 7 8 9 10 11 12 | <!-- PHP Code --> <!DOCTYPE html> <html> <head> <title>PHP Hello World</title> </head> <body> <?php echo "Hello, World!"; ?> </body> </html> |
Exercise 10.2: Variables and Data Types
Description : Write a PHP script that declares variables for a student’s name, age, and grade, and displays them on a web page.
Syllabus Coverage : Variables, primitive data types.
Aim : Teach students how to declare and use variables in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!-- PHP Code --> <!DOCTYPE html> <html> <head> <title>PHP Variables</title> </head> <body> <?php $name = "Alice"; $age = 20; $grade = "A"; echo "Name: $name<br>"; echo "Age: $age<br>"; echo "Grade: $grade<br>"; ?> </body> </html> |
Exercise 10.3: Arrays
Description : Write a PHP script that creates an array of student names and displays them in a list format.
Syllabus Coverage : Arrays.
Aim : Introduce students to arrays and their usage in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!-- PHP Code --> <!DOCTYPE html> <html> <head> <title>PHP Arrays</title> </head> <body> <?php $students = ["Alice", "Bob", "Charlie"]; echo "<h3>Student List:</h3>"; echo "<ul>"; foreach ($students as $student) { echo "<li>$student</li>"; } echo "</ul>"; ?> </body> </html> |
Exercise 10.4: Control Structures
Description : Write a PHP script that checks if a number is even or odd and displays the result.
Syllabus Coverage : Control structures (selection).
Aim : Teach students how to use conditional statements in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!-- PHP Code --> <!DOCTYPE html> <html> <head> <title>PHP Control Structures</title> </head> <body> <?php $number = 10; if ($number % 2 == 0) { echo "$number is even."; } else { echo "$number is odd."; } ?> </body> </html> |
Exercise 10.5: Loops
Description : Write a PHP script that prints numbers from 1 to 10 using a loop.
Syllabus Coverage : Control structures (repetition).
Aim : Teach students how to use loops in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!-- PHP Code --> <!DOCTYPE html> <html> <head> <title>PHP Loops</title> </head> <body> <?php echo "<h3>Numbers from 1 to 10:</h3>"; for ($i = 1; $i <= 10; $i++) { echo "$i<br>"; } ?> </body> </html> |
Exercise 10.6: Functions
Description : Write a PHP script that defines a function to calculate the area of a rectangle and calls it with user-provided values.
Syllabus Coverage : Functions, parameter passing, return values.
Aim : Introduce students to writing reusable functions in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!-- PHP Code --> <!DOCTYPE html> <html> <head> <title>PHP Functions</title> </head> <body> <?php function calculateArea($length, $width) { return $length * $width; } $length = 5; $width = 3; $area = calculateArea($length, $width); echo "The area of the rectangle is $area."; ?> </body> </html> |
Exercise 10.7: Forms and User Input
Description : Write a PHP script that creates a form to collect a user’s name and displays a greeting message.
Syllabus Coverage : Forms, input elements, GET/POST methods.
Aim : Teach students how to handle user input using forms in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!-- PHP Code --> <!DOCTYPE html> <html> <head> <title>PHP Forms</title> </head> <body> <form method="post" action=""> <label for="name">Enter your name:</label> <input type="text" id="name" name="name"> <button type="submit">Submit</button> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = htmlspecialchars($_POST['name']); echo "<h3>Hello, $name!</h3>"; } ?> </body> </html> |
Exercise 10.8: Connecting to a Database
Description : Write a PHP script that connects to a MySQL database, creates a table, inserts data, and retrieves it.
Syllabus Coverage : Database connectivity, working with databases.
Aim : Introduce students to database operations using PHP and MySQL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <!-- PHP Code --> <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test_db"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create table $sql = "CREATE TABLE IF NOT EXISTS students ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, age INT )"; $conn->query($sql); // Insert data $conn->query("INSERT INTO students (name, age) VALUES ('Alice', 20)"); // Retrieve data $result = $conn->query("SELECT * FROM students"); echo "<h3>Students:</h3>"; while ($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Age: " . $row["age"] . "<br>"; } $conn->close(); ?> |
Exercise 10.9: Dynamic Web Pages with PHP and MySQL
Description : Write a PHP script that dynamically displays a list of products fetched from a MySQL database.
Syllabus Coverage : Creating dynamic web pages, retrieving data from MySQL.
Aim : Teach students how to create dynamic web pages by integrating PHP with MySQL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!-- PHP Code --> <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "products_db"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Retrieve data $result = $conn->query("SELECT * FROM products"); echo "<h3>Product List:</h3>"; while ($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Price: $" . $row["price"] . "<br>"; } $conn->close(); ?> |
Exercise 10.10: File Handling
Description : Write a PHP script that reads a text file and displays its contents on a web page.
Syllabus Coverage : File handling (basic file operations).
Aim : Teach students how to read and display file contents using PHP.
1 2 3 4 5 6 7 | <!-- PHP Code --> <?php $filename = "example.txt"; if (file_exists($filename)) { $content = file_get_contents($filename); echo "[crayon-67c1669bd18eb052370809 ]$content |
”;
} else {
echo “File not found.”;
}
?>
[/crayon]
Exercise 10.11: Session Management
Description : Write a PHP script that uses sessions to track the number of times a user visits a page.
Syllabus Coverage : Sessions.
Aim : Introduce students to session management in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 | <!-- PHP Code --> <?php session_start(); if (!isset($_SESSION['visits'])) { $_SESSION['visits'] = 0; } $_SESSION['visits']++; echo "You have visited this page " . $_SESSION['visits'] . " times."; ?> |
Below are advanced PHP exercises that go beyond the syllabus, exploring real-world applications and advanced concepts. These exercises will help you deepen your understanding of PHP and its capabilities in web development, backend programming, and integration with modern technologies.
Exercise 1: RESTful API Development
Description : Build a simple RESTful API using PHP to manage a list of products (CRUD operations).
What You Learn : REST principles, JSON handling, HTTP methods (GET
, POST
, PUT
, DELETE
).
Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <?php header("Content-Type: application/json"); // Simulated database $products = [ ["id" => 1, "name" => "Laptop", "price" => 1000], ["id" => 2, "name" => "Phone", "price" => 500] ]; $method = $_SERVER['REQUEST_METHOD']; $input = json_decode(file_get_contents('php://input'), true); switch ($method) { case 'GET': echo json_encode($products); break; case 'POST': $newProduct = $input; $newProduct['id'] = count($products) + 1; $products[] = $newProduct; echo json_encode(["message" => "Product added", "product" => $newProduct]); break; case 'PUT': $id = $input['id']; foreach ($products as &$product) { if ($product['id'] == $id) { $product['name'] = $input['name']; $product['price'] = $input['price']; echo json_encode(["message" => "Product updated", "product" => $product]); break; } } break; case 'DELETE': $id = $input['id']; $products = array_filter($products, function ($product) use ($id) { return $product['id'] != $id; }); echo json_encode(["message" => "Product deleted"]); break; default: http_response_code(405); echo json_encode(["error" => "Method Not Allowed"]); } ?> |
Exercise 2: Authentication System
Description : Create a user login and registration system with password hashing and session management.
What You Learn : User authentication, password hashing, sessions, and security practices.
Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php session_start(); // Simulated database $users = [["username" => "admin", "password" => password_hash("password123", PASSWORD_DEFAULT)]]; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username']; $password = $_POST['password']; foreach ($users as $user) { if ($user['username'] === $username && password_verify($password, $user['password'])) { $_SESSION['username'] = $username; echo json_encode(["message" => "Login successful"]); exit; } } echo json_encode(["error" => "Invalid credentials"]); } ?> <!-- Login Form --> <form method="POST" action=""> <label for="username">Username:</label> <input type="text" id="username" name="username"> <label for="password">Password:</label> <input type="password" id="password" name="password"> <button type="submit">Login</button> </form> |
Exercise 3: File Upload and Management
Description : Build a PHP script to upload files to the server and display a list of uploaded files.
What You Learn : File handling, file uploads, directory operations.
Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php $uploadDir = "uploads/"; if (!is_dir($uploadDir)) { mkdir($uploadDir, 0777, true); } if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $file = $_FILES['file']; $filePath = $uploadDir . basename($file['name']); if (move_uploaded_file($file['tmp_name'], $filePath)) { echo "File uploaded successfully."; } else { echo "Error uploading file."; } } $files = scandir($uploadDir); echo "<h3>Uploaded Files:</h3>"; foreach ($files as $file) { if ($file !== "." && $file !== "..") { echo "<a href='$uploadDir$file'>$file</a><br>"; } } ?> <!-- File Upload Form --> <form method="POST" enctype="multipart/form-data"> <label for="file">Upload File:</label> <input type="file" id="file" name="file"> <button type="submit">Upload</button> </form> |
Exercise 4: Email Sending
Description : Write a PHP script to send emails using the PHPMailer
library.
What You Learn : Email sending, SMTP configuration, third-party libraries.
Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php'; $mail = new PHPMailer(true); try { // Server settings $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'your_email@example.com'; $mail->Password = 'your_password'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; // Recipients $mail->setFrom('your_email@example.com', 'Your Name'); $mail->addAddress('recipient@example.com', 'Recipient Name'); // Content $mail->isHTML(true); $mail->Subject = 'Test Email'; $mail->Body = 'This is a test email sent using PHPMailer.'; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } ?> |
Exercise 5: Real-Time Chat Application
Description : Build a real-time chat application using PHP, AJAX, and WebSocket or long polling.
What You Learn : Real-time communication, AJAX, WebSocket/long polling.
Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <?php // Simulated chat storage $messagesFile = "messages.json"; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $message = $_POST['message']; $messages = json_decode(file_get_contents($messagesFile), true) ?? []; $messages[] = $message; file_put_contents($messagesFile, json_encode($messages)); echo json_encode(["status" => "success"]); } else { $messages = json_decode(file_get_contents($messagesFile), true) ?? []; echo json_encode($messages); } ?> <!-- Chat Interface --> <div id="chat-box"></div> <input type="text" id="message-input"> <button onclick="sendMessage()">Send</button> <script> function loadMessages() { fetch('chat.php') .then(response => response.json()) .then(messages => { const chatBox = document.getElementById('chat-box'); chatBox.innerHTML = messages.map(msg => `<div>${msg}</div>`).join(''); }); } function sendMessage() { const message = document.getElementById('message-input').value; fetch('chat.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `message=${encodeURIComponent(message)}` }).then(() => loadMessages()); } setInterval(loadMessages, 1000); </script> |
Exercise 6: Payment Gateway Integration
Description : Integrate a payment gateway (e.g., PayPal, Stripe) into a PHP application.
What You Learn : Payment processing, API integration, secure transactions.
Code Example (Stripe):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php require 'vendor/autoload.php'; \Stripe\Stripe::setApiKey('your_stripe_secret_key'); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $token = $_POST['stripeToken']; $amount = $_POST['amount']; try { $charge = \Stripe\Charge::create([ 'amount' => $amount * 100, 'currency' => 'usd', 'source' => $token, 'description' => 'Test Charge' ]); echo "Payment successful!"; } catch (\Stripe\Exception\ApiErrorException $e) { echo "Payment failed: " . $e->getMessage(); } } ?> <!-- Payment Form --> <form action="" method="POST"> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="your_stripe_public_key" data-amount="1000" data-name="Demo Site" data-description="Test Payment" data-currency="usd"> </script> </form> |
Exercise 7: Web Scraping
Description : Use PHP to scrape data from a website and store it in a database.
What You Learn : Web scraping, DOM parsing, database integration.
Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $html = file_get_contents('https://example.com'); $dom = new DOMDocument(); @$dom->loadHTML($html); $xpath = new DOMXPath($dom); $elements = $xpath->query('//h1'); foreach ($elements as $element) { echo $element->nodeValue . "<br>"; } ?> |
Exercise 8: GraphQL API
Description : Build a GraphQL API using PHP to query and mutate data.
What You Learn : GraphQL, schema design, querying and mutating data.
Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php require 'vendor/autoload.php'; use GraphQL\Type\Schema; use GraphQL\GraphQL; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\ObjectType; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'hello' => [ 'type' => Type::string(), 'resolve' => function () { return 'Hello, world!'; } ] ] ]); $schema = new Schema([ 'query' => $queryType ]); $rawInput = file_get_contents('php://input'); $input = json_decode($rawInput, true); $query = $input['query']; try { $result = GraphQL::executeQuery($schema, $query); echo json_encode($result->toArray()); } catch (\Exception $e) { echo json_encode(['error' => $e->getMessage()]); } ?> |
These exercises cover advanced topics like API development , authentication , file handling , email sending , real-time communication , payment gateway integration , web scraping , and GraphQL . They provide practical, real-world applications of PHP and will help you explore areas beyond the syllabus.