Adv PHP Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Title: Advanced PHP Course Lab Manual

Exercise 1: Basic Form Handling

Theory

PHP's `$_GET` and `$_POST` superglobals are used to collect data from HTML forms. The `$_POST`
method is more secure for handling sensitive data as it does not expose form data in the URL.

Exercise Steps

1. Create an HTML form with fields `username` and `password`.

2. Write a PHP script to handle form submissions using the POST method.

3. Display the submitted data on the next page.

Code:

```php

// form.php

<form action="process_form.php" method="POST">

Username: <input type="text" name="username"><br>

Password: <input type="password" name="password"><br>

<input type="submit" value="Submit">

</form>

```

```php

// process_form.php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$username = $_POST['username'];

$password = $_POST['password'];

echo "Username: $username<br>Password: $password";

}
```

---

Exercise 2: Form Validation and Sanitization

Theory

Validating and sanitizing user input is crucial to avoid security risks. Validation ensures that input
data meets specific criteria, while sanitization cleans input to prevent attacks like XSS and SQL
injection.

Exercise Steps

1. Modify the form from Exercise 1 to include an email field.

2. Implement server-side validation to ensure all fields are filled.

3. Sanitize the email field to remove invalid characters.

Code

```php

// process_form.php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo "Invalid email format";

} else {

echo "Email: $email";

```
---

Exercise 3: Handling Multiple Form Inputs

Theory

PHP can process multiple inputs from forms, such as checkboxes and multi-select dropdowns, by
using arrays. These inputs allow users to select multiple values.

Exercise Steps

1. Create an HTML form with checkboxes for selecting programming languages.

2. Process the selected options in PHP and display the selected languages.

Sample Code:

```php

// multi_checkbox_form.php

<form action="handle_multi_checkbox.php" method="POST">

<input type="checkbox" name="languages[]" value="PHP"> PHP<br>

<input type="checkbox" name="languages[]" value="JavaScript"> JavaScript<br>

<input type="checkbox" name="languages[]" value="Python"> Python<br>

<input type="submit" value="Submit">

</form>

```

```php

// handle_multi_checkbox.php

if (isset($_POST['languages'])) {

foreach ($_POST['languages'] as $language) {

echo htmlspecialchars($language) . "<br>";


}

} else {

echo "No language selected.";

```

---

Exercise 4: Dropdown Handling and Processing

Theory

Dropdowns in forms can be handled similarly to checkboxes, especially when allowing multiple
selections. PHP can process the selected options and manage them as arrays.

Exercise Steps

1. Create a form with a multi-select dropdown to choose favorite fruits.

2. Write a PHP script to handle and display the selected fruits.

Code:

```php

// multi_select_fruit_form.php

<form action="handle_fruit.php" method="POST">

<select name="fruits[]" multiple>

<option value="Apple">Apple</option>

<option value="Banana">Banana</option>

<option value="Cherry">Cherry</option>

</select>

<input type="submit" value="Submit">


</form>

```

```php

// handle_fruit.php

if (!empty($_POST['fruits'])) {

foreach ($_POST['fruits'] as $fruit) {

echo htmlspecialchars($fruit) . "<br>";

} else {

echo "No fruits selected.";

```

---

Exercise 5: File Upload Handling

Theory

PHP allows users to upload files using forms. The `$_FILES` superglobal is used to manage file
uploads, including checking file types and moving files to the desired directory.

Exercise Steps

1. Create a form for uploading an image.

2. Write a PHP script to handle the upload, check the file type, and move it to the `uploads`
directory.

Code

```php

// upload_form.php
<form action="upload_file.php" method="POST" enctype="multipart/form-data">

Select image to upload:

<input type="file" name="fileToUpload" id="fileToUpload">

<input type="submit" value="Upload Image">

</form>

```

```php

// upload_file.php

$target_dir = "uploads/";

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Check if file is an actual image

$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);

if ($check !== false) {

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded.";

} else {

echo "Sorry, there was an error uploading your file.";

} else {

echo "File is not an image.";

```

---

Exercise 6: Connecting PHP to MySQL

Theory
PHP can interact with MySQL databases using extensions like `mysqli` or `PDO`. Establishing a
database connection is the first step in performing CRUD operations.

Steps

1. Set up a MySQL database and create a table for storing user data.

2. Write a PHP script to connect to the database and display a success message if the connection is
successful.

Code

```php

// db_connect.php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "myDatabase";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

echo "Connected successfully";

```

---

Exercise 7: Inserting Data into MySQL

Theory
Inserting data into a MySQL database from a PHP script involves executing an SQL `INSERT`
statement. Data is typically inserted into specific table columns.

Exercise Steps

1. Extend the connection script to insert user data into a table.

2. Create an HTML form to collect user data and submit it to the PHP script.

Code:

```php

// insert_user.php

$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {

echo "New record created successfully";

} else {

echo "Error: " . $sql . "<br>" . $conn->error;

$conn->close();

```

---

Exercise 8: Retrieving Data from MySQL

Theory

PHP retrieves data from a MySQL database using the `SELECT` statement. The results are typically
displayed in a loop, processing each row returned by the query.

Exercise Steps
1. Create a PHP script to retrieve and display all records from the users table.

2. Format the output in an HTML table.

Code:

```php

// retrieve_data.php

$sql = "SELECT id, name, email FROM users";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

echo "<table><tr><th>ID</th><th>Name</th><th>Email</th></tr>";

while($row = $result->fetch_assoc()) {

echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["email"]."</td></tr>";

echo "</table>";

} else {

echo "0 results";

$conn->close();

```

---

Exercise 9: Updating Data in MySQL

Theory

Updating existing records in a MySQL database is done with the `UPDATE` statement, specifying the
columns to be changed and the criteria for selecting records.
Exercise Steps

1. Write a PHP script to update a user's email address based on their ID.

2. Use a form to accept the new email address and the user's ID.

Code:

```php

// update_data.php

$sql = "UPDATE users SET email='newemail@example.com' WHERE id=1";

if ($conn->query($sql) === TRUE) {

echo "Record updated successfully";

} else {

echo "Error updating record: " . $conn->error;

$conn->close();

```

---

Exercise 10: Deleting Data from MySQL

Theory

The `DELETE` statement is used in PHP to remove records from a MySQL table. It is important to use
this operation cautiously, often with

confirmation to avoid accidental data loss.


Exercise Steps

1. Create a PHP script to delete a user record based on their ID.

2. Implement a confirmation step before the deletion.

Code:

```php

// delete_data.php

$sql = "DELETE FROM users WHERE id=1";

if ($conn->query($sql) === TRUE) {

echo "Record deleted successfully";

} else {

echo "Error deleting record: " . $conn->error;

$conn->close();

```

---

Exercise 11: Creating a Registration Form with MySQL

Theory

Registration forms collect user details and store them in a database. This exercise combines form
handling and MySQL integration to create a complete registration system.

Exercise Steps

1. Create an HTML registration form with fields for name, email, and password.

2. Write a PHP script to insert the submitted data into a MySQL table.
3. Include validation and hashing of passwords for security.

Code

```php

// registration_form.php

<form action="register.php" method="POST">

Name: <input type="text" name="name"><br>

Email: <input type="email" name="email"><br>

Password: <input type="password" name="password"><br>

<input type="submit" value="Register">

</form>

```

```php

// register.php

$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

$sql = "INSERT INTO users (name, email, password) VALUES ('".$_POST['name']."',


'".$_POST['email']."', '$password')";

if ($conn->query($sql) === TRUE) {

echo "Registration successful";

} else {

echo "Error: " . $sql . "<br>" . $conn->error;

```

---

Exercise 12: Building a Simple Login System

Theory
A login system checks user credentials against a database. If the credentials match, the user is
granted access; otherwise, they are denied.

Exercise Steps

1. Create a login form with fields for email and password.

2. Write a PHP script to validate the submitted credentials against stored data.

3. Implement session management to maintain the logged-in state.

Code:

```php

// login.php

session_start();

$email = $_POST['email'];

$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE email='$email'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

$row = $result->fetch_assoc();

if (password_verify($password, $row['password'])) {

$_SESSION['user'] = $row['name'];

echo "Login successful";

} else {

echo "Invalid password";

} else {

echo "No user found with this email";


}

$conn->close();

Exercise 13: Implementing a Logout Functionality

Theory

Logging out of a system involves destroying the user’s session, ensuring that access is terminated,
and the user is redirected to a login page.

Exercise Steps

1. Create a logout link or button.

2. Write a PHP script to destroy the session and redirect the user to the login page.

Code:

```php

// logout.php

session_start();

session_unset();

session_destroy();

header("Location: login.php");

```

---

Exercise 14: Introduction to MVC in PHP

Theory
The MVC (Model-View-Controller) architecture separates the application into three interconnected
components: Model (data), View (user interface), and Controller (business logic). This design pattern
helps in organizing code and managing complex projects.

Exercise Steps

1. Create directories for Models, Views, and Controllers.

2. Develop a basic MVC structure to display a list of users from a database.

Code:

```php

// model/User.php

class User {

private $conn;

public function __construct($db) {

$this->conn = $db;

public function getAllUsers() {

$sql = "SELECT * FROM users";

return $this->conn->query($sql);

```

```php

// controller/UserController.php

include '../model/User.php';

include '../config/Database.php';
class UserController {

private $model;

public function __construct($db) {

$this->model = new User($db);

public function displayUsers() {

$users = $this->model->getAllUsers();

include '../view/UserView.php';

php

// view/UserView.php

foreach ($users as $user) {

echo "Name: " . $user['name'] . "<br>Email: " . $user['email'] . "<br>";

Exercise 15: Creating a Complete MVC Application

Theory

Building a complete MVC application integrates all components—Model, View, and Controller—into
a cohesive structure. This exercise consolidates the learning from previous exercises to create a
simple blog application.

Exercise Steps

1. Set up the MVC structure with directories for Models, Views, and Controllers.

2. Develop the Model to interact with the database, the Controller to handle requests, and the Views
to display blog posts.
3. Implement CRUD operations for blog posts.

Code

```php

// model/Post.php

class Post {

private $conn;

public function __construct($db) {

$this->conn = $db;

public function getAllPosts() {

$sql = "SELECT * FROM posts";

return $this->conn->query($sql);

public function createPost($title, $content) {

$sql = "INSERT INTO posts (title, content) VALUES ('$title', '$content')";

return $this->conn->query($sql);

```

```php

// controller/PostController.php

include '../model/Post.php';

include '../config/Database.php';

class PostController {
private $model;

public function __construct($db) {

$this->model = new Post($db);

public function displayPosts() {

$posts = $this->model->getAllPosts();

include '../view/PostView.php';

public function addPost($title, $content) {

$this->model->createPost($title, $content);

header("Location: index.php");

```

```php

// view/PostView.php

foreach ($posts as $post) {

echo "<h2>" . $post['title'] . "</h2>";

echo "<p>" . $post['content'] . "</p>";

```

You might also like