Adv PHP Lab Manual
Adv PHP Lab Manual
Adv PHP Lab Manual
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
2. Write a PHP script to handle form submissions using the POST method.
Code:
```php
// form.php
</form>
```
```php
// process_form.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
}
```
---
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
Code
```php
// process_form.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
} else {
```
---
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
2. Process the selected options in PHP and display the selected languages.
Sample Code:
```php
// multi_checkbox_form.php
</form>
```
```php
// handle_multi_checkbox.php
if (isset($_POST['languages'])) {
} else {
```
---
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
Code:
```php
// multi_select_fruit_form.php
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Cherry">Cherry</option>
</select>
```
```php
// handle_fruit.php
if (!empty($_POST['fruits'])) {
} else {
```
---
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
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">
</form>
```
```php
// upload_file.php
$target_dir = "uploads/";
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
} else {
} else {
```
---
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";
if ($conn->connect_error) {
```
---
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
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')";
} else {
$conn->close();
```
---
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.
Code:
```php
// retrieve_data.php
$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 {
$conn->close();
```
---
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
} else {
$conn->close();
```
---
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
Code:
```php
// delete_data.php
} else {
$conn->close();
```
---
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>
```
```php
// register.php
} else {
```
---
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
2. Write a PHP script to validate the submitted credentials against stored data.
Code:
```php
// login.php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
$_SESSION['user'] = $row['name'];
} else {
} else {
$conn->close();
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
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");
```
---
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
Code:
```php
// model/User.php
class User {
private $conn;
$this->conn = $db;
return $this->conn->query($sql);
```
```php
// controller/UserController.php
include '../model/User.php';
include '../config/Database.php';
class UserController {
private $model;
$users = $this->model->getAllUsers();
include '../view/UserView.php';
php
// view/UserView.php
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;
$this->conn = $db;
return $this->conn->query($sql);
return $this->conn->query($sql);
```
```php
// controller/PostController.php
include '../model/Post.php';
include '../config/Database.php';
class PostController {
private $model;
$posts = $this->model->getAllPosts();
include '../view/PostView.php';
$this->model->createPost($title, $content);
header("Location: index.php");
```
```php
// view/PostView.php
```