Unit 4
Unit 4
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
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
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)
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
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)
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:
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.