Web Framework and Services — Study Notes

Unit 02

File Operations, Cookies, Mail & Exceptions

4 Questions 5 Marks Each Web Framework and Services
01
5 Marks Question

Explain File Operations in PHP

File operations in PHP allow developers to create, open, read, write, close, copy, rename, and manipulate files on the server. PHP provides several built-in functions for performing these operations.

Common File Operations

01
Opening a File — fopen()

The fopen() function opens a file and returns a file pointer or resource that can be used for further operations.

Example: $file = fopen("data.txt", "r");

Common modes: r for read, w for write, and a for append.

02
Reading a File — fread()

The fread() function reads data from an already opened file.

$data = fread($file, 100);

Here, 100 represents the maximum number of bytes to read.

03
Writing to a File — fwrite()

The fwrite() function writes data into an open file.

$file = fopen("data.txt", "w");
fwrite($file, "Hello PHP");

PHP also provides file_put_contents(), which writes data directly to a file and creates the file if it does not exist.

file_put_contents("data.txt", "Hello PHP");
04
Closing a File — fclose()

After performing file operations, fclose() is used to close the open file.

fclose($file);
05
Other File Operations

PHP also provides functions such as file_exists(), copy(), and rename().

Function Purpose
file_exists()Checks whether a file or directory exists.
copy()Copies a file from one location to another.
rename()Renames or moves a file.
Example:
<?php
$file = fopen("sample.txt", "w");
fwrite($file, "Welcome to PHP");
fclose($file);
?>
This program opens or creates a file, writes data into it, and then closes it.
Conclusion PHP file operations provide an easy way to manage server-side files using functions such as fopen(), fread(), fwrite(), and fclose().
02
5 Marks Question

Explain the Concept of Cookies and Session

Cookies and sessions are used in PHP to store user-related information and maintain data across different web pages.

1. Cookies

A cookie is a small piece of information stored in the client's browser memory or hard disk. A cookie contains a name and value and can store information such as username, last visit time, and similar details.

Cookies allow information to be passed between different web pages.

<?php
setcookie("UserName", "IQRA", time() + 3600);
?>

Here, the cookie stores "IQRA" under the name UserName.

Accessing a cookie: echo $_COOKIE["UserName"];

To delete a cookie, its expiration time is set to a time in the past.

setcookie("UserName", "", time() - 3600);

2. Session

A session is a temporary storage area on the server used to store information about a user while they are visiting a website. Each user receives a unique Session ID, which allows the server to identify the user.

A session is started using session_start(), and session variables are created using the $_SESSION superglobal.

<?php
session_start();
$_SESSION["UserName"] = "IQRA";
?>

Accessing a session:

<?php
session_start();
echo $_SESSION["UserName"];
?>

A session can be destroyed using session_destroy();

Difference Between Cookie and Session

Cookie Session
Data is stored on the client side.Data is stored on the server side.
Used for information such as username and last visit.Used for temporary user information during a visit.
Can remain until its expiration time.Exists for the user's session.
Less secure because data is stored on client.More secure because actual data remains on server.
Conclusion Both cookies and sessions maintain user information across pages, but cookies store data on the client, whereas sessions store data on the server.
03
5 Marks Question

Explain the mail() Function in PHP

The mail() function is a built-in PHP function used to send emails directly from a PHP script. It sends email through the web server's configured mail service.

It is commonly used for contact forms, registration confirmation, password reset, OTP verification, notifications, and feedback forms.

Syntax

mail(to, subject, message, headers, parameters);

Parameters

Parameter Description
toEmail address of the recipient
subjectSubject of the email
messageBody or content of the email
headersAdditional information such as sender, CC, BCC and Reply-To
parametersOptional command-line parameters

Example

<?php
$to = "student@example.com";
$subject = "Welcome";
$message = "Welcome to our website!";
$headers = "From: admin@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully";
} else {
    echo "Email sending failed";
}
?>

The function returns TRUE if the email is accepted by the mail server and FALSE if it cannot be sent.

Email Headers

Headers provide additional information about the email. Common headers include From, Reply-To, CC, BCC, and Content-Type. Headers are passed as the fourth parameter of mail().

Conclusion The PHP mail() function provides a simple way to send emails from web applications and is useful for notifications, confirmations, password resets, OTPs, and contact forms.
04
5 Marks Question

Explain Exception Handling in PHP

Exception handling is a mechanism used to handle unexpected events or errors that occur during program execution. These unexpected events are called exceptions and can disrupt the normal flow of a program.

PHP mainly uses try, throw, catch, and finally for exception handling.

1. try Block

The try block contains the code that may cause an exception.

try {
    $result = 10 / 2;
    echo $result;
}

2. throw Keyword

The throw keyword is used to manually generate an exception. PHP then looks for a catch block to handle it.

if ($age < 18) {
    throw new Exception("Age must be 18 or above");
}

3. catch Block

The catch block is executed when an exception occurs inside the try block. It is used to handle the exception.

catch (Exception $e) {
    echo "Exception occurred";
}

4. finally Block

The finally block always executes, whether an exception occurs or not. It is useful for cleanup operations such as closing a database connection.

finally {
    echo "Program Finished";
}

Complete Example

<?php
try {
    $age = 15;

    if ($age < 18) {
        throw new Exception("Age must be 18 or above");
    }

    echo "Valid Age";
}
catch (Exception $e) {
    echo "Exception occurred";
}
finally {
    echo "Program Finished";
}
?>
Flow: try → throw → catch → finally
Conclusion Exception handling allows PHP programs to handle unexpected situations in a controlled manner instead of disrupting the normal execution of the application.