Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
28 views33 pages

Unit 4

The document covers PHP's built-in date and time functions, including how to manipulate dates and connect to MySQL databases using MySQLi and PDO. It also explains file handling in PHP, including reading, writing, and deleting files, as well as form handling techniques for processing user input. Security best practices for database interactions and examples of CRUD operations are provided throughout the document.

Uploaded by

KUNAL SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views33 pages

Unit 4

The document covers PHP's built-in date and time functions, including how to manipulate dates and connect to MySQL databases using MySQLi and PDO. It also explains file handling in PHP, including reading, writing, and deleting files, as well as form handling techniques for processing user input. Security best practices for database interactions and examples of CRUD operations are provided throughout the document.

Uploaded by

KUNAL SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit 4

Date and Time Functions in PHP-


PHP provides built-in date and time functions that allow developers to:
 Get the current date and time
 Format date/time
 Perform date arithmetic
 Compare or calculate differences between dates
This becomes especially powerful when used with mathematical operations like:
 Calculating age
 Finding a number of days between two dates
 Adding or subtracting days/months/years
 Displaying future or past dates
Common Date/Time Functions in PHP

Function Description
date() Formats a timestamp into a readable date/time
time() Returns the current Unix timestamp
strtotime() Converts a date/time string to a Unix timestamp
mktime() Creates a timestamp from a date
Calculates the difference between two dates (returns
date_diff()
DateInterval object)
date_create() Creates a new DateTime object

Example 1: Display Current Date and Time


<?php
echo "Today is: " . date("Y-m-d") . "<br>";
echo "Current Time: " . date("h:i:s A");
?>
Output
Today is: 2025-04-16
Current Time: 09:45:20 AM
Example 2: Calculate Age from Birth Date
<?php
$birthDate = "2004-10-28";
$today = date("Y-m-d");
$age = date_diff(date_create($birthDate), date_create($today));
echo "Your age is: " . $age->y . " years.";
?>
Output
Your age is: 24 years.
Example 3: Add or Subtract Days from a Date
<?php
$today = date("Y-m-d");
$nextWeek = date('Y-m-d', strtotime("+7 days"));
$lastWeek = date('Y-m-d', strtotime("-7 days"));
echo "Today: $today<br>";
echo "Next Week: $nextWeek<br>";
echo "Last Week: $lastWeek";
?>
Example 4: Calculate Number of Days Between Two Dates
<?php
$startDate = "2025-01-01";
$endDate = "2025-04-16";
$diff = date_diff(date_create($startDate), date_create($endDate));
echo "Number of days between dates: " . $diff->days;
?>
Output
Number of days between dates: 105
Example 5: Calculate Days Left Until a Future Event
<?php
$today = new DateTime();
$examDate = new DateTime("2025-05-13");
$interval = $today->diff($examDate);
echo "Days left until exam: " . $interval->days . " days"
?>
Example 6: Convert a Human-Readable Date to Timestamp and Back
<?php
$dateString = "10 May 2000";
$timestamp = strtotime($dateString);
echo "Timestamp: " . $timestamp . "<br>";
echo "Formatted Date: " . date("Y-m-d", $timestamp);
?>
Example 7: Countdown Timer (Minutes Remaining)
<?php
$now = time();
$end = strtotime("2025-04-16 18:00:00");
$remainingMinutes = round(($end - $now) / 60);
echo "Time remaining until 6 PM: $remainingMinutes minutes";
?>
What is a Database?
A database is a structured collection of data that allows easy access, management, and
updating. In web development, MySQL is one of the most commonly used databases with
PHP.
What is MySQL?
MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP. MySQL is developed, distributed, and supported by
Oracle Corporation.
The data in a MySQL database are stored in tables which consists of columns and rows.
MySQL is a database system that runs on a server.
MySQL is ideal for both small and large applications.
MySQL is very fast, reliable, and easy to use database system. It uses standard SQL
MySQL compiles on a number of platforms.
How to connect PHP with MySQL Database?
PHP 5 and later can work with a MySQL database using:
 MySQLi extension.
 PDO (PHP Data Objects).
Difference Between MySQLi and PDO
Feature MySQLi PDO (PHP Data Objects)
Works with 12+ different
Database
Works only with MySQL databases (e.g., MySQL,
Support
PostgreSQL, SQLite, etc.)
Supports both object-
Supports only object-
API Style oriented and procedural
oriented style
styles
High – code can be reused
with different databases by
Portability Low – tied to MySQL changing only the connection
string and minimal query
syntax

Ease of
Difficult – requires Easy – minimal changes
Switching
rewriting most of the code needed
Databases

Named
Placeholders Not supported Supported
in Queries
Slightly faster with Slightly slower but more
Performance
MySQL flexible

There are three ways of working with MySQl and PHP


1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO
Connecting to MySQL database using PHP
There are 3 ways in which we can connect to MySQl from PHP as listed above and described
below:
1. Using MySQLi object-oriented procedure: We can use the MySQLi object-oriented
procedure to establish a connection to MySQL database from a PHP script.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Explanation: We can create an instance of the mysqli class providing all the necessary details
required to establish the connection such as host, username, password etc. If the instance is
created successfully then the connection is successful otherwise there is some error in
establishing connection.
2. Using MySQLi procedural procedure : There is also a procedural approach of MySQLi to
establish a connection to MySQL database from a PHP script as described below.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Explanation: In MySQLi procedural approach instead of creating an instance we can use the
mysqli_connect() function available in PHP to establish a connection. This function takes the
information as arguments such as host, username , password , database name etc. This function
returns MySQL link identifier on successful connection or FALSE when failed to establish a
connection.
2. Using PDO procedure: PDO stands for PHP Data Objects. That is, in this method we
connect to the database using data objects in PHP as described below:
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Explanation: The exception class in PDO is used to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the script stops
executing and flows directly to the first catch(){ } block.
Closing A Connection
When we establish a connection to MySQL database from a PHP script , we should also
disconnect or close the connection when our work is finished. Here we have described the
syntax of closing the connection to a MySQL database in all 3 methods described above. We
have assumed that the reference to the connection is stored in $conn variable.
1. Using MySQLi object oriented procedure
Syntax
$conn->close();
2. Using MySQLi procedural procedure
Syntax
mysqli_close($conn);
3. Using PDO procedure
Syntax
$conn = null;
Steps to Access and Manipulate a Database Using PHP
Step 1: Connect to MySQL Database
You need to use mysqli_connect() to connect PHP to MySQL.
$conn = mysqli_connect("localhost", "root", "", "class");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
 "localhost": Server
 "root": Username
 "": Password (empty by default for localhost)
 "class": Your database name
Step 2: Create a Table (once via PHP or directly in MySQL)
$sql = "CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
grade VARCHAR(10)
)";
mysqli_query($conn, $sql);
3. CRUD Operations in PHP (Create, Read, Update, Delete)
A. Create (Insert Data)
$name = "John";
$age = 18;
$grade = "A";
$sql = "INSERT INTO students (name, age, grade) VALUES ('$name', $age, '$grade')";
mysqli_query($conn, $sql);
B. Read (Retrieve Data)
$sql = "SELECT * FROM students";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row['name'] . " - Grade: " . $row['grade'] . "<br>";
}
C. Update (Modify Data)
$sql = "UPDATE students SET grade='B' WHERE name='John'";
mysqli_query($conn, $sql);
D. Delete (Remove Data)
$sql = "DELETE FROM students WHERE name='John'";
mysqli_query($conn, $sql);
4. Using HTML Forms with PHP to Manipulate Database
Form Example (HTML + PHP)
<form method="post" action="insert.php">
Name: <input type="text" name="name"><br>
Age: <input type="number" name="age"><br>
Grade: <input type="text" name="grade"><br>
<input type="submit" value="Save">
</form>
insert.php
$conn = mysqli_connect("localhost", "root", "", "testdb");
$name = $_POST['name'];
$age = $_POST['age'];
$grade = $_POST['grade'];
$sql = "INSERT INTO students (name, age, grade) VALUES ('$name', $age, '$grade')";
mysqli_query($conn, $sql);
echo "Record inserted successfully!";
5. Security Best Practices
 Use prepared statements or PDO to avoid SQL Injection
 Always validate and sanitize user input
Example using prepared statement:
$stmt = $conn->prepare("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $age, $grade); // s = string, i = integer
$stmt->execute();

PHP File Handling


In PHP, File handling is the process of interacting with files on the server, such as reading files,
writing to a file, creating new files, or deleting existing ones. File handling is essential for
applications that require the storage and retrieval of data, such as logging systems, user-
generated content, or file uploads.
Types of File Operations in PHP
Several types of file operations can be performed in PHP:
 Reading Files: PHP allows you to read data from files either entirely or line by line.
 Writing to Files: You can write data to a file, either overwriting existing content or
appending to the end.
 File Metadata: PHP allows you to gather information about files, such as their size,
type, and last modified time.
 File Uploading: PHP can handle file uploads via forms, enabling users to submit files
to the server.
Common File Handling Functions in PHP
 fopen() – Opens a file
 fclose() – Closes a file
 fread() – Reads data from a file
 fwrite() – Writes data to a file
 file_exists() – Checks if a file exists
 unlink() – Deletes a file
Opening and Closing Files
Before you can read or write to a file, you need to open it using the fopen() function, which
returns a file pointer resource. Once you’re done working with the file, you should close it
using fclose() to free up resources.
<?php
// Open the file in read mode
$file = fopen("gfg.txt", "r");
if ($file) {
echo "File opened successfully!";
fclose($file); // Close the file
} else {
echo "Failed to open the file.";
}
?>
File Modes in PHP
Files can be opened in any of the following modes:
“w” – Opens a file for writing only. If the file does not exist, then a new file is created, and if
the file already exists, then the file will be truncated (the contents of the file are erased).
“r” – File is open for reading only.
“a” – File is open for writing only. The file pointer points to the end of the file. Existing data
in the file is preserved.
“w+” – Opens file for reading and writing both. If the file does not exist, then a new file is
created, and if the file already exists, then the contents of the file are erased.
“r+” – File is open for reading and writing both.
“a+” – File is open for write/read. The file pointer points to the end of the file. Existing data in
the file is preserved. If the file is not there, then a new file is created.
“x” – New file is created for write only.
Reading from Files
There are two ways to read the contents of a file in PHP. These are –
1. Reading the Entire File
You can read the entire content of a file using the fread() function or the file_get_contents()
function.
<?php
$file = fopen("gfg.txt", "r");
$content = fread($file, filesize("gfg.txt"));
echo $content;
fclose($file);
?>
2. Reading a File Line by Line
You can use the fgets() function to read a file line by line.
<?php
$file = fopen("gfg.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}
fclose($file);
}
?>
Writing to Files
You can write to files using the fwrite() function. It writes data to an open file in the specified
mode.
<?php
// Open the file in write mode
$file = fopen("gfg.txt", 'w');
if ($file) {
$text = "Hello world\n";
fwrite($file, $text);
fclose($file);
}
?>
Deleting Files
Use the unlink() function to delete the file in PHP.
<?php
if (file_exists("gfg.txt")) {
unlink("gfg.txt");
echo "File deleted successfully!";
} else {
echo "File does not exist.";
}
?>
PHP Form Handling
Form handling is the process of collecting and processing information that users submit through
HTML forms. In PHP, we use special tools called $_POST and $_GET to gather the data from
the form. Which tool to use depends on how the form sends the data—either through the POST
method (more secure, hidden in the background) or the GET method (data is visible in the
URL).
 Collecting Data: Retrieving form data using PHP.
 Validating Data: Ensuring that the input meets expected formats.
 Sanitizing Data: Cleaning up the data to prevent malicious content.
 Processing Data: Using the data for its intended purpose (e.g., saving to a database,
sending an email, etc.).
 Returning a Response: Displaying feedback to the user or redirecting them to another
page.
Form Attributes
action: The action attribute specifies the URL where the form data will be sent when the form
is submitted.
<form method="post" action="process_form.php">
method: The method attribute specifies the HTTP method (GET or POST) to use when sending
form data.
<form method="post" action="process_form.php">
name: The name attribute is crucial in PHP form handling, as it is used to refer to the data
submitted by the form fields.
$username = $_POST['username']; // Accessing the form data
target: The target attribute specifies where to display the response after submitting the form.
It determines where the resulting page (or response) will appear once the form is submitted.
<form method="post" action="process_form.php" target="_blank">
<input type="text" name="username" required>
<input type="submit" value="Submit">
</form>
enctype: The enctype (encoding type) attribute defines how the form data should be encoded
when submitted to the server. This is particularly important when submitting forms that include
file uploads.
Form Elements
Form processing contains a set of controls through which the client and server can
communicate and share information. The controls used in forms are:
Input Field: Input field is the most common form element, allowing users to input a single
line of text, such as their name, address, or any other simple text information.
<input type="text" name="fullname" required>
Password Input Field: The password input field hides the text entered, making it suitable for
secure data entry like passwords.
<input type="password" name="password" required>
Checkboxes: Checkboxes allow users to select multiple options from a set of choices. They
are often used for lists of features or permissions.
<input type="checkbox" name="subscribe" value="yes"> Subscribe to newsletter
Radio Buttons: Radio buttons allow the user to choose only one option from a set of predefined
options. This is useful for binary choices, such as gender selection.
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="male"> Male
Textarea: The textarea element allows users to input multiple lines of text, making it useful
for longer messages, feedback, or comments.
<textarea name="message" rows="5" cols="40" required></textarea>
Creating a Simple Form
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">
<table>
<tr>
<td>Full Name:</td>
<td><input type="text" name="fullname"></td>
</tr>
<tr>
<td>Email Address:</td>
<td><input type="email" name="user_email"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="user_age"></td>
</tr>
<tr>
<td>Feedback:</td>
<td><textarea name="user_feedback" rows="4" cols="40"></textarea></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type="radio" name="user_gender" value="female">Female
<input type="radio" name="user_gender" value="male">Male
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
<?php
$fullname = $user_email = $user_gender = $user_feedback = $user_age = "";
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Only process the POST data if the form is submitted
if (isset($_POST['fullname'])) {
$fullname = htmlspecialchars($_POST['fullname']);
}
if (isset($_POST['user_email'])) {
$user_email = htmlspecialchars($_POST['user_email']);
}
if (isset($_POST['user_age'])) { // Corrected variable to user_age
$user_age = htmlspecialchars($_POST['user_age']);
}
if (isset($_POST['user_feedback'])) {
$user_feedback = htmlspecialchars($_POST['user_feedback']);
}
if (isset($_POST['user_gender'])) {
$user_gender = htmlspecialchars($_POST['user_gender']);
}
}
// Display the submitted details
echo "<h2>Details Submitted:</h2>";
echo "Full Name: " . $fullname . "<br>";
echo "Email: " . $user_email . "<br>";
echo "Age: " . $user_age . "<br>";
echo "Feedback: " . $user_feedback . "<br>";
echo "Gender: " . $user_gender;
?>
</body>
</html>
File Upload in PHP
File uploading allows users to select a file from their device (such as a document or image) and
send it to the server, where PHP can process and store it. PHP provides an easy way to handle
file uploads securely and efficiently.
How to Upload a File?
The process of uploading a file follows these steps −
1. User Opens the Upload Page:
The user navigates to a web page that contains an HTML form. This form includes:
 A text field displaying the selected file name
 A Browse button (<input type="file">)
 A Submit button (<input type="submit">)
2. User Selects a File:
The user clicks the Browse button and selects a file from their local computer.
3. Selected File Path Appears:
The full path (or just the file name, depending on the browser) appears in the file input field.
4. Form Submission:
The user clicks the Submit button, and the form sends the selected file to the web server using
the POST method and multipart/form-data encoding.
5. File Stored Temporarily on Server:
The file is temporarily stored in the server's temporary directory, typically with a system-
generated name. This is handled by PHP automatically.
6. PHP Script Handles the Upload:
The PHP script specified in the action attribute of the form:
 Uses the $_FILES superglobal to access the uploaded file
 Validates the file (e.g., size, type, errors)
 Moves the file from the temporary location to a permanent directory using
move_uploaded_file()
7. Confirmation Message:
The PHP script then displays a confirmation message to the user indicating whether the file
was uploaded successfully or not.
Configuring File Upload Settings in PHP
To successfully upload files using PHP, you need to ensure your PHP configuration (php.ini)
is set correctly. This configuration controls file size limits, temporary storage, and the overall
behavior of file uploads.
1. Locate the php.ini File
 This is the main configuration file for PHP.
 You can find its location by creating a PHP file with: <?php phpinfo(); ?>
2. PHP php.ini Settings for File Uploads

Directive Description
file_uploads Enables or disables file uploads
upload_max_filesize Maximum size of an uploaded file

post_max_size Maximum size of POST data (includes files and form fields)

Maximum number of files that can be uploaded


max_file_uploads
simultaneously
upload_tmp_dir Directory for temporary uploaded files
max_input_time Maximum time allowed to parse input data (form + files)

Open the "php.ini" file and ensure that the following settings are enabled by removing the
leading semicolon (;) symbol in file_uploads, upload_tmp_dir, upload_max_filesize and
max_file_uploads parameters −
Recommended Configuration Settings
file_uploads = On
upload_max_filesize = 10M
post_max_size = 20M
max_file_uploads = 20
upload_tmp_dir = "C:\xampp\tmp" ; or /tmp on Linux
max_input_time = 60
3. Restart Your Web Server After Changes
After updating php.ini, you must restart your web server (e.g., Apache or Nginx) for the
changes to take effect.
For XAMPP (Windows):
 Open XAMPP Control Panel
 Stop and start Apache

For Linux (Apache):


sudo systemctl restart apache2
4. Check Upload Limits in PHP
Run this code to check your current limits:
<?php
echo 'Max file upload size: ' . ini_get('upload_max_filesize') . "<br>";
echo 'Max POST size: ' . ini_get('post_max_size') . "<br>";
?>
What is Image Generation in PHP?
The imagecreate() function is an inbuilt function in PHP which is used to create a new image.
This function returns the blank image of given size. In general imagecreatetruecolor() function
is used instead of imagecreate() function because imagecreatetruecolor() function creates high
quality images.
For Example,
 Draw shapes (lines, rectangles, circles)
 Add text to images
 Create charts or CAPTCHA
 Output or save images in formats like PNG, JPEG, or GIF
Syntex:
imagecreate( $width, $height )
Parameters: This function accepts two parameters as mentioned above and described below:
 $width: It is a mandatory parameter used to specify the image width.
 $height: It is a mandatory parameter used to specify the image height.
Return Value: This function returns an image resource identifier on success, FALSE on errors.
Below programs illustrate the imagecreate() function in PHP.
<?php
// Create the size of image or blank image
$image = imagecreate(500, 300);
// Set the background color of image
$background_color = imagecolorallocate($image, 0, 153, 0);
// Set the text color of image
$text_color = imagecolorallocate($image, 255, 255, 255);
// Function to create image which contains string.
imagestring($image, 5, 180, 100, "GeeksforGeeks", $text_color);
imagestring($image, 3, 160, 120, "A computer science portal", $text_color);
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>
Output:

Algorithm to Generate an Image in PHP


Create a PNG image with a custom message.
1. Start
2. Set the width and height of the image
3. Create a blank image canvas using imagecreatetruecolor()
4. Allocate background and text colors using imagecolorallocate()
5. Fill the background color using imagefill()
6. Draw text on the image using imagestring() or imagettftext()
7. Set the Content-type to image/png
8. Output the image using imagepng()
9. Destroy the image resource to free memory
10. End
PHP Cookies
Cookies in PHP are used for maintaining state and storing user-specific information across
multiple page visits. Since HTTP is a stateless protocol, every page request is independent,
making it difficult to remember user preferences, authentication status, or other details between
visits. Cookies allow data to be stored on the client’s browser, enabling websites to “remember”
users and their interactions.
What Are Cookies in PHP?
A cookie is a small text file that is stored in the user’s browser. Cookies are used to store
information that can be retrieved later, making them ideal for scenarios where you need to
remember user preferences, such as:
 User login status (keeping users logged in between sessions)
 Language preferences
 Shopping cart contents
 Tracking user activity for analytics purposes
Cookies in PHP are created using the setcookie() function. When a cookie is set, the data is
stored in the user’s browser and sent to the server with each subsequent request made by the
browser.
Syntax:
setcookie(name, value, expire, path, domain, security);
 Name: It is used to set the name of the cookie.
 Value: It is used to set the value of the cookie.
 Expire: It is used to set the expiry timestamp of the cookie, after which the cookie can’t
be accessed.
 Path: It is used to specify the path on the server for which the cookie will be available.
 Domain: It is used to specify the domain for which the cookie is available.
 Security: It is used to indicate that the cookie should be sent only if a secure HTTPS
connection exists.
How Do Cookies Work?
Cookies work in the following ways:
 Setting Cookies: A cookie is set using the setcookie() function in PHP. The cookie data
is stored on the user’s browser and sent along with each HTTP request to the server.
 Reading Cookies: Once a cookie is set, it can be accessed using the $_COOKIE
superglobal array. This allows you to retrieve cookie values that were set on the user’s
browser.
 Expiration of Cookies: Cookies can be set to expire after a certain period. When a
cookie expires, it is automatically deleted by the browser. Cookies can also be manually
deleted by calling the setcookie() function with a past expiration date.
 Sending Cookies to the Browser: Cookies are sent to the browser as HTTP headers.
Since HTTP headers must be sent before any actual content (HTML, etc.), setcookie()
must be called before any output is sent to the browser.
How to Use Cookies in PHP?
1. Creating Cookies
Create a cookie named Auction_Item and assign the value Luxury Car to it. The cookie will
expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created.";
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
</body>
</html>
Output:

In this example:
 The setcookie() function is used to create a cookie named “Auction_Item” with the
value “Luxury Car”. The cookie will expire in 2 days (calculated as time() + 2 * 24 *
60 * 60).
 The echo statement prints the message “cookie is created.” on the webpage, confirming
that the cookie has been set.
 The cookie will expire after 2 days from the current time, meaning the browser will
store it for that period before it’s automatically deleted.
 The note tells the user that they might need to reload the page to see the value of the
cookie, as the cookie data is available after the page is refreshed.
2. Checking Whether a Cookie Is Set Or Not
It is always advisable to check whether a cookie is set or not before accessing its value.
Therefore, to check whether a cookie is set or not, the PHP isset() function is used. To
check whether a cookie “Auction_Item” is set or not, the isset() function is executed as
follows:
Example: This example describes checking whether the cookie is set or not.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Output:
In this example:
 The setcookie() function is used to create a cookie named “Auction_Item” with the
value “Luxury Car”. The cookie will expire after 2 days from the current time (time()
+ 2 * 24 * 60 * 60).
 The isset($_COOKIE[“Auction_Item”]) checks if the cookie “Auction_Item” exists. If
it exists, it displays the message “Auction Item is a Luxury Car”. If the cookie doesn’t
exist, it displays “No items for auction.”.
 Depending on whether the cookie is set, the page will show either the auction item
(Luxury Car) or a message indicating there are no items for auction.
 The note explains that the user might have to reload the page to see the value of the
cookie because cookies are sent with the next request, which typically requires a page
reload.
3. Accessing Cookie Values
For accessing a cookie value, the PHP $_COOKIE superglobal variable is used. It is an
associative array that contains a record of all the cookies values sent by the browser in the
current request. The records are stored as a list where the cookie name is used as the key.
To access a cookie named “Auction_Item”, the following code can be executed.
Example: This example describes accessing & modifying the cookie value.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Output:
In this example:
 The PHP function setcookie() is used to create a cookie named “Auction_Item” with
the value “Luxury Car”. The cookie is set to expire after 2 days (time() + 2 * 24 * 60 *
60), meaning it will remain in the user’s browser for 2 days.
 The code attempts to display the value of the cookie Auction_Item by using
$_COOKIE[“Auction_Item”]. This will output the value of the cookie (which is
“Luxury Car”) on the page if the cookie is set and accessible.
 The note advises the user that they may need to reload the page to see the value of the
cookie. This is because cookies are sent with the HTTP request during subsequent page
loads, so the value will not be immediately available on the first page load.
 On the initial page load, the cookie is set but not yet sent to the server. Therefore, trying
to access the cookie immediately after setting it will result in an undefined value for
$_COOKIE[“Auction_Item”] on the first request. A page reload is required for the
cookie to be available.
 The echo statement outputs the value of the cookie Auction_Item on the page. However,
since the cookie is set in the same script, its value will not be available until the page is
reloaded.
4. Deleting Cookies
The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie()
function is called by passing the cookie name and other arguments or empty strings, however,
this time, the expiration date is required to be set in the past. To delete a cookie named
“Auction_Item”, the following code can be executed.
Example: This example describes the deletion of the cookie value.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
setcookie("Auction_Item", "", time() - 60);
?>
<?php
echo "cookie is deleted";
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>

In this example:
 The setcookie() function is used to create a cookie named “Auction_Item” with the
value “Luxury Car”. The cookie is set to expire in 2 days (time() + 2 * 24 * 60 * 60).
 The setcookie() function is called again, but this time with an empty value for the
“Auction_Item” cookie and an expiration time set to 1 minute ago (time() – 60). This
effectively deletes the cookie by instructing the browser to remove it.
 The message “cookie is deleted” is displayed on the page using the echo statement,
indicating that the cookie has been deleted.
 The note informs the user that they might need to reload the page to see the value of the
cookie, which is true for both setting and deleting cookies. After the page reloads, the
cookie will be deleted and no longer available.
Use Cases for Cookies
Cookies are used in various scenarios, including:
1. User Authentication: Cookies can be used to keep users logged in between sessions. For
example, when a user logs in, a session ID or a token can be stored in a cookie. On later visits,
the website can check the cookie and log the user in automatically.
<?php
// Store login token in a cookie (for example, after a successful login)
setcookie("login_token", $token, time() + 3600, "/"); // Expires in 1 hour
?>
2. User Preferences: Cookies are useful for remembering user settings, such as theme
preferences, language settings, or page layout preferences.
<?php
// Store theme preference in a cookie
setcookie("theme", "dark", time() + 3600, "/");
?>
3. Shopping Carts: For e-commerce sites, cookies are commonly used to store the contents of
a user’s shopping cart. This allows users to continue shopping after they leave the site and
return later.
<?php
// Store shopping cart items in a cookie (as a serialized array or JSON string)
$cart = json_encode(["item1" => 2, "item2" => 1]);
setcookie("cart", $cart, time() + 3600, "/");
?>
4. Tracking and Analytics: Cookies can be used to track user behavior on a website. This data
can be used for analytics or to provide personalized content based on past interactions.
<?php
// Set a cookie to track user visits
setcookie("visit_count", ++$_COOKIE["visit_count"], time() + 3600, "/");
?>
PHP Sessions
PHP sessions are a tool used to store user-specific data across multiple pages during a single
visit to a website. They solve the problem of maintaining a state in a stateless environment,
where each page load is independent. Without sessions, a website would not be able to
remember user information, such as login status or preferences, between different pages.
What is a PHP Session?
A session in PHP is a mechanism that allows data to be stored and accessed across multiple
pages on a website. When a user visits a website, PHP creates a unique session ID for that user.
This session ID is then stored as a cookie in the user’s browser (by default) or passed via the
URL. The session ID helps the server associate the data stored in the session with the user
during their visit.
PHP sessions are used to maintain state, meaning they allow data to persist as users navigate
through a site, which would otherwise be stateless (i.e., each request is independent).
Example: If a user logs in to a website, their login status can be stored in a session variable.
As the user moves through different pages, the login status can be checked using the session
variable.
How Do PHP Sessions Work?
 Session Start: When a user accesses a PHP page, the session gets started with the
session_start() function. This function initiates the session and makes the session data
available through the $_SESSION superglobal array.
 Session Variables: Data that needs to be carried across different pages is stored in the
$_SESSION array. For example, a user’s name or login status can be stored in this
array.
 Session ID: PHP assigns a unique session ID to every user. This session ID is stored in
a cookie in the user’s browser by default. The session ID is used to retrieve the user-
specific data on each page load.
 Session Data Storage: The session data is stored on the server, not the client side. By
default, PHP stores session data in a temporary file on the server. The location of this
storage is determined by the session.save_path directive in the php.ini file.
 Session Termination: Sessions can be terminated by calling session_destroy(), which
deletes the session data. Alternatively, a session can be closed using
session_write_close() to save the session data and free up server resources.
How to Use PHP Sessions?
Using PHP sessions involves several key steps: starting a session, storing data in session
variables, retrieving data, and eventually destroying the session when no longer needed.
1. Starting a Session
To begin using sessions in PHP, you need to start the session with session_start() at the very
beginning of the PHP script. This function ensures that the session is available and creates a
unique session ID if it doesn’t already exist.
<?php
session_start(); // Start the session
?>
Note: Always call session_start() before any HTML output in your PHP script. If you output
HTML or whitespace before calling session_start(), it will cause an error.
2. Storing Data in Sessions
Once the session is started, you can store any information in the $_SESSION superglobal array.
This allows you to carry data across different pages on the website.
<?php
session_start();
$_SESSION['username'] = 'GFG'; // Store session data
$_SESSION['user_id'] = 123;
?>
The username and user ID are stored in the session for use on other pages.
3. Retrieving Session Data
Once data is stored in a session, it can be accessed on any page where the session is started.
<?php
session_start();
echo $_SESSION['username']; // Output: GFG
?>
You can use the session variables to display user-specific information, check login statuses,
and perform various operations.
4. Checking if Session Variables Exist
Before using session data, it’s a good practice to check if the session variable exists to avoid
errors.
<?php
session_start();
if (isset($_SESSION['username'])) {
echo "Welcome, " . $_SESSION['username'];
} else {
echo "Please log in.";
}
?>
5. Destroying Sessions
When a session is no longer needed, you can terminate it by using session_destroy(). This
function removes all session data from the server. However, it does not automatically unset
session variables; you need to manually clear them using unset() if needed.
<?php
session_start();
unset($_SESSION['username']); // Remove specific session variable
session_destroy(); // Destroy the session
?>
If you want to log out the user, destroying the session will remove all user-specific data and
effectively “log them out.”
PHP Session Functions
PHP provides several built-in functions to work with sessions. Below are some of the most
commonly used functions:
 session_start(): Starts a session or resumes the current session.
session_start(); // Start a session
 $_SESSION: The $_SESSION superglobal array holds session data. You can store and
retrieve session data through this array.
$_SESSION['user_id'] = 1; // Store data
echo $_SESSION['user_id']; // Retrieve data
 session_destroy(): Destroys all data registered to a session.
session_start();
session_destroy(); // Ends the session
 session_regenerate_id(): Regenerates the session ID to enhance security by avoiding
session attacks.
session_regenerate_id(true); // Regenerate the session ID
Why Use PHP Sessions?
 Maintaining User State: In web development, each page request is stateless, meaning
the server doesn’t remember any previous interaction. Sessions allow you to store and
retrieve user data (like login status or shopping cart contents) across multiple pages,
making the web experience feel seamless.
 Secure Data Storage: Unlike cookies, which store data on the client side (in the
browser), sessions store data on the server. This makes sessions more secure for
handling sensitive information, as the data is not exposed to the user or tampered with
on the client side.
 Personalized User Experience: Sessions enable you to personalize user experiences
by remembering details such as user preferences, authentication status, and choices
made on previous pages. For example, a logged-in user’s name can be displayed on
every page they visit.
 E-commerce and Shopping Carts: For e-commerce websites, sessions are crucial to
keep track of items in a shopping cart. Without sessions, the cart would be reset each
time the user navigates to a different page, leading to a frustrating experience.
 Security: PHP sessions help to prevent unauthorized access. Sensitive data such as
authentication tokens or user credentials can be stored securely in session variables,
reducing the risk of exposure.
Advantages of PHP Sessions
The advantages of PHP Sessions are mentioned below:
 Security: Unlike cookies, which store data on the client side, sessions store data on the
server, making them more secure for sensitive information.
 Data Persistence: Sessions allow data to persist across multiple pages during a user’s
visit to a site, making it ideal for tracking user activities like login status, shopping cart
contents, etc.
 Efficiency: Sessions do not require constant data transfer between the client and server,
unlike cookies that send data with each request.
 Automatic Expiration: PHP sessions can be configured to automatically expire after
a certain time of inactivity, which helps in maintaining session security.
Comparison between PHP Sessions and Cookies:
Feature PHP Sessions Cookies
Storage Location Server-side Client-side (browser)
Data Visibility Not visible to user Visible in browser storage
More secure (data stored on Less secure (can be modified on client-
Security
server) side)
Can store large amounts of
Storage Capacity Limited to ~4KB
data

Until browser is closed (by Can have long expiry (days, months,
Data Lifetime
default) or expired manually years)

Slightly slower (server


Performance Faster (data stored in browser)
reads/writes)
session_start() and
Setup Method setcookie() and $_COOKIE array
$_SESSION array

Managed through PHP Must manually encode/decode complex


Data Handling
internally data

Use Case Login sessions, shopping cart,


Remember username, theme preference
Examples form tracking
Tamper Low (can be modified using browser
High (stored on server)
Protection tools)

Server Load Higher (data stored on server) Lower (data stored on client)

HTTP authentication
We are in big doors to the digital era where comfort is the main driver. Enjoying all the
convenience right from ordering merchandise and paying bills to get services while sitting on
the couch. This is how we developed the internet to work for us.
Here, authentication comes in and every web resource wants to know who you are because
your details are their asset as well as responsibility to keep it safe. This security is maintained
by HTTP which is a set of rules that determines how data is exchanged between
resources. HTTP authentication is a scenario of secure communication between users and
online resources. Let’s understand what is HTTP authentication and other know-hows of its
working to ensure security in the digital world.
What is HTTP Authentication?
HTTP Authentication is a security mechanism to verify the user who is eligible to access the
web resource. It involves communication between client and server using HTTP header where
server requests user’s credentials for authentication. The client in response provides the
information in the header. Here’s the concept is based on web authentication through HTTP
standards to ensure the security of users’ information. The more secured version is HTTPS,
here S stands for Security Socket Layer (SSL) to establish encryption in communication. There
are many schemes of HTTP authentication based on the security requirement and to make the
credentials insufficient to crack the access for hackers.
Let’s drive you to some of the most used authentication schemes to enable access with security
mode.
HTTP Authentication Schemes: The server determines various authentication schemes for
the client to choose from. Schemes are the methods of authentication over the web. Present you
the list of authentication schemes to make the concept clear.
Basic authentication: It is a challenge-response paradigm wherein the server requests
credentials and in response client provides a username and password for authentication. It is a
single factor authentication where the information is exchanged in clear text format.
Digest authentication: It is a more secure version of the basic authentication with the
challenge-response procedure in addition to nonce value and MD5 algorithm to encrypt the
data. Nonce value includes more information in credentials to level up the security.
Bearer authentication: Commonly known as token-based authentication with the multi-factor
security mechanism. It adds an additional layer to the single-level security with the tokens to
verify the credentials received from actual users. JWT (JSON Web Token) is a widely used
medium for bearer.
NTLM: It’s an abbreviation of New Technology LAN Manager, a security protocol by
windows to perform authentication of user’s identity without credentials and allow access to
the resource.
Negotiate authentication: It is an updated version of NTLM that uses the Kerberos protocol
as an authentication provider. Kerberos is faster and securer than NTLM.
The above schemes are used with a scale of security requirements of the web resource. The
‘Basic’ provides the lowest level of security while the other ones are used in the case of high-
security requirements.
How does HTTP Authentication work?
HTTP has a general framework to control the access of the user to web resources. This
framework depends on Authentication headers. Headers assist the users on how to provide their
credentials and which scheme is used in the process. There are two types of headers WWW-
Authenticate header and Proxy Authentication header.
The header syntax looks like this:
 WWW-Authenticate: <type> realm=<realm>
 Proxy-Authenticate: <type> realm=<realm>
Here, <type> specifies the scheme used in the authentication process. <realm> describes the
scope of security to the client. Now, here’s a process of how HTTP authentication works with
both the headers and maintains a paradigm in the process.
1. Request: The client makes a request to access the resource as an anonymous identity.
The server doesn’t have any information about the client visiting the page.
2. Challenge: After detecting a visitor, the server responds to the client with 401
(Unauthorized) response status as a challenge to verify the identity and instructions on
how to verify the in the header (eg: WWW-Authenticate).
3. Response: The client responds to the server’s challenge with the required credentials
commonly, username, and password to authenticate the identity and access the resource.
4. Proxy Authentication: In case you use a proxy server to verify as an intended client,
the proxy server challenge client with 407 (proxy) authentication status. Here, the
proxy server gives authentication on behalf of the client to access the resource.
5. Verification: After receiving the credentials (also through proxy header) the server
verifies them and if they are not valid, the server sends 403 (forbidden) response status.
In case credentials prove to be valid, the client receives a welcome note.
These are some easy-to-grasp steps for HTTP authentication. The process is a whole lot more
complicated in the back-end systems. With every possible way emerging to crack the access
by hackers, security is added up with the layers on the existing mechanisms. Starting from
Single-factor authentication, Two Factor Authentication, and how Multi-factor Authentication
is widely a need of an hour. Banking and e-commerce services use strict multi-layer security
mechanisms to ensure social security to data including payment details. Hence, HTTP protocol
ensures safe communication between resources over the internet.
System Call
A system call in PHP refers to executing an operating system command directly from a PHP
script. PHP provides several functions that allow:
 Run Linux/Windows commands
 Access shell utilities (like ls, mkdir, copy, etc.)
 Execute batch scripts or shell scripts
 Capture the output of system-level operations
This is commonly used when PHP application needs to:
 Perform file operations
 Control hardware or OS behavior
 Run external programs
 Automate server tasks (e.g., backups, cleanup, etc.)
Introduction of System Call
A system call is a programmatic way in which a computer program requests a service from the
kernel of the operating system on which it is executed. A system call is a way for programs
to interact with the operating system. A computer program makes a system call when it
requests the operating system’s kernel. System call provides the services of the operating
system to the user programs via the Application Program Interface(API). System calls are the
only entry points into the kernel system and are executed in kernel mode.
 A user program can interact with the operating system using a system call. A number
of services are requested by the program, and the OS responds by launching a number
of systems calls to fulfill the request.
 A system call can be written in high-level languages like C or Pascal or in assembly
language. If a high-level language is used, the operating system may directly invoke
system calls, which are predefined functions.
 A system call is initiated by the program executing a specific instruction, which triggers
a switch to kernel mode, allowing the program to request a service from the OS. The
OS then handles the request, performs the necessary operations, and returns the result
back to the program.
 System calls are essential for the proper functioning of an operating system, as they
provide a standardized way for programs to access system resources. Without system
calls, each program would need to implement its methods for accessing hardware and
system services, leading to inconsistent and error-prone behavior.
Services Provided by System Calls
 Process Creation and Management
 Main Memory Management
 File Access, Directory, and File System Management
 Device Handling(I/O)
 Protection
 Networking, etc.
o Process Control: end, abort, create, terminate, allocate, and free memory.
o File Management: create, open, close, delete, read files, etc.
o Device Management
o Information Maintenance
o Communication
Features of System Calls
 Interface: System calls provide a well-defined interface between user programs and
the operating system. Programs make requests by calling specific functions, and the
operating system responds by executing the requested service and returning a result.
 Protection: System calls are used to access privileged operations that are not available
to normal user programs. The operating system uses this privilege to protect the system
from malicious or unauthorized access.
 Kernel Mode: When a system call is made, the program is temporarily switched from
user mode to kernel mode. In kernel mode, the program has access to all system
resources, including hardware, memory, and other processes.
 Context Switching: A system call requires a context switch, which involves saving the
state of the current process and switching to the kernel mode to execute the requested
service. This can introduce overhead, which can impact system performance.
 Error Handling: System calls can return error codes to indicate problems with the
requested service. Programs must check for these errors and handle them appropriately.
 Synchronization: System calls can be used to synchronize access to shared resources,
such as files or network connections. The operating system provides synchronization
mechanisms, such as locks or semaphores, to ensure that multiple programs can access
these resources safely.
How does System Call Work?
Here is a detailed explanation step by step how system calls work:
 Users need special resources: Sometimes programs need to do some special things
that can’t be done without the permission of the OS like reading from a file, writing to
a file, getting any information from the hardware, or requesting a space in memory.
 The program makes a system call request: There are special predefined instructions
to make a request to the operating system. These instructions are nothing but just a
“system call”. The program uses these system calls in its code when needed.
 Operating system sees the system call: When the OS sees the system call then it
recognizes that the program needs help at this time so it temporarily stops the program
execution and gives all the control to a special part of itself called ‘Kernel’. Now
‘Kernel’ solves the need of the program.
 The operating system performs the operations: Now the operating system performs
the operation that is requested by the program. Example: reading content from a file
etc.
 Operating system give control back to the program : After performing the special
operation, OS give control back to the program for further execution of program.
Types of System Calls
Services provided by an OS are typically related to any kind of operation that a user program
can perform like creation, termination, forking, moving, communication, etc. Similar types of
operations are grouped into one single system call category. System calls are classified into the
following categories:
Examples of a System Call in Windows and Unix
System calls for Windows and Unix come in many different forms. These are listed in the table
below as follows:

Process Windows Unix

CreateProcess() Fork()
Process Control ExitProcess() Exit()
WaitForSingleObject() Wait()

Open()
CreateFile()
Read()
File manipulation ReadFile()
Write()
WriteFile()
Close()

SetConsoleMode() Ioctl()
Device Management ReadConsole() Read()
WriteConsole() Write()

GetCurrentProcessID() Getpid()
Information Maintenance SetTimer() Alarm()
Sleep() Sleep()

CreatePipe() Pipe()
Communication CreateFileMapping() Shmget()
MapViewOfFile() Mmap()

SetFileSecurity() Chmod()
Protection InitializeSecurityDescriptor() Umask()
SetSecurityDescriptorgroup() Chown()

Open(): Accessing a file on a file system is possible with the open() system call. It gives the
file resources it needs and a handle the process can use. A file can be opened by multiple
processes simultaneously or just one process. Everything is based on the structure and file
system.
Read(): Data from a file on the file system is retrieved using it. In general, it accepts three
arguments:
 A description of a file.
 A buffer for read data storage.
 How many bytes should be read from the file
Before reading, the file to be read could be identified by its file descriptor and opened
using the open() function.
Wait(): In some systems, a process might need to hold off until another process has finished
running before continuing. When a parent process creates a child process, the execution of the
parent process is halted until the child process is complete. The parent process is stopped using
the wait() system call. The parent process regains control once the child process has finished
running.
Write(): Data from a user buffer is written using it to a device like a file. A program can
produce data in one way by using this system call. generally, there are three arguments:
 A description of a file.
 A reference to the buffer where data is stored.
 The amount of data that will be written from the buffer in bytes.
Fork(): The fork() system call is used by processes to create copies of themselves. It is one of
the methods used the most frequently in operating systems to create processes. When a parent
process creates a child process, the parent process’s execution is suspended until the child
process is finished. The parent process regains control once the child process has finished
running.
Exit(): A system call called exit() is used to terminate a program. In environments with
multiple threads, this call indicates that the thread execution is finished. After using the exit()
system function, the operating system recovers the resources used by the process.

You might also like