0% found this document useful (0 votes)
4 views24 pages

Unit 4

This document provides an introduction to PHP, covering its syntax, variables, data types, operators, loops, and arrays. It explains how to use PHP for web development, including the creation of constants and the different scopes of variables. Additionally, it details various PHP operators and functions, demonstrating their usage with examples.

Uploaded by

manishanchara4
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)
4 views24 pages

Unit 4

This document provides an introduction to PHP, covering its syntax, variables, data types, operators, loops, and arrays. It explains how to use PHP for web development, including the creation of constants and the different scopes of variables. Additionally, it details various PHP operators and functions, demonstrating their usage with examples.

Uploaded by

manishanchara4
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/ 24

Introduction to PHP

PHP (Hypertext Preprocessor) is a widely-used, open-source server-side scripting language specifically


suited for web development. It is embedded within HTML and is known for its ability to generate
dynamic web page content. PHP scripts are executed on the server, and the result is sent back to the
browser as plain HTML.
Basic Syntax
1. PHP Tags PHP code is written between special tags: <?php ... ?>. These tags tell the server to
execute the code within them.
<?php
// PHP code goes here
?>
2. Statements PHP statements end with a semicolon (;). It's required to tell the PHP interpreter
where each statement ends.
<?php
echo "Hello, World!"; // Outputs: Hello, World!
?>
3. Case Sensitivity PHP is case-sensitive for variable names, but function names are not case-
sensitive.
<?php
$myVariable = "This is case-sensitive";
echo $myvariable; // Error, as $myvariable is not the same as $myVariable
?>
4. Echo and Print echo and print are used to output data to the screen. echo can output multiple
values, while print returns a value (1), so it can be used in expressions.
<?php
echo "Hello ", "World!"; // Outputs: Hello World!
print "PHP Basics"; // Outputs: PHP Basics
?>

PHP Variables
Variables are "containers" for storing information. A variable can have a short name (like $x and $y) or
a more descriptive name ($age, $carname, $total_volume).
Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)

Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
$txt = "W3Schools.com";
echo "I love $txt!";

Example
$txt = "W3Schools.com";
echo "I love " . $txt . "!";

Variable Types
PHP has no command for declaring a variable, and the data type depends on the value of the variable.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource
Get the Type
To get the data type of a variable, use the var_dump() function.
Example
The var_dump() function returns the data type and the value:
$x = 5;
var_dump($x);
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Example
$x = "John";
echo $x;

Assign Multiple Values


You can assign the same value to multiple variables in one line:
Example
All three variables get the value "Fruit":
$x = $y = $z = "Fruit";

PHP Variables Scope


In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static

Global Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function:
Example
Variable with global scope:
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";

Local Scope
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
Example
Variable with local scope:
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";

PHP The global Keyword


The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15

PHP The static Keyword


Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes
we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();

PHP Constants
Constants are like variables, except that once they are defined they cannot be changed or undefined.
A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Note: Unlike variables, constants are automatically global across the entire script.
To create a constant, use the define() function.
Syntax
define(name, value);
Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
Example
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;

PHP const Keyword


You can also create a constant by using the const keyword.
Example
Create a case-sensitive constant with the const keyword:
const MYCAR = "Volvo";
echo MYCAR;

PHP Constant Arrays


From PHP7, you can create an Array constant using the define() function.
Example
Create an Array constant:
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0];

Constants are Global: Constants are automatically global and can be used across the entire script.

PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations,
such as addition, subtraction, multiplication etc.

Operator Name Example Result Try it

+ Addition $x + $y Sum of $x and $y Try it »

- Subtraction $x - $y Difference of $x and $y Try it »

* Multiplication $x * $y Product of $x and $y Try it »

/ Division $x / $y Quotient of $x and $y Try it »

% Modulus $x % $y Remainder of $x divided by $y Try it »

** Exponentiation $x ** $y Result of raising $x to the $y'th power Try it »

PHP Assignment Operators


The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the
assignment expression on the right.

Assignment Same as... Description Try it

x=y x=y The left operand gets set to the value of the Try it »
expression on the right

x += y x=x+y Addition Try it »

x -= y x=x-y Subtraction Try it »

x *= y x=x*y Multiplication Try it »

x /= y x=x/y Division Try it »

x %= y x=x%y Modulus
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result Try it

== Equal $x == $y Returns true if $x is equal to Try it »


$y

=== Identical $x === $y Returns true if $x is equal to Try it »


$y, and they are of the same
type

!= Not equal $x != $y Returns true if $x is not Try it »


equal to $y

<> Not equal $x <> $y Returns true if $x is not Try it »


equal to $y

!== Not identical $x !== $y Returns true if $x is not Try it »


equal to $y, or they are not of
the same type

> Greater than $x > $y Returns true if $x is greater Try it »


than $y

< Less than $x < $y Returns true if $x is less than Try it »


$y

>= Greater than or equal to $x >= $y Returns true if $x is greater Try it »


than or equal to $y

<= Less than or equal to $x <= $y Returns true if $x is less than Try it »
or equal to $y

<=> Spaceship $x <=> $y Returns an integer less than, Try it »


equal to, or greater than
zero, depending on if $x is
less than, equal to, or greater
than $y. Introduced in PHP
7.

PHP Increment / Decrement Operators


The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.

Operator Same as... Description Try it

++$x Pre-increment Increments $x by one, then returns $x Try it »

$x++ Post-increment Returns $x, then increments $x by one Try it »

--$x Pre-decrement Decrements $x by one, then returns $x Try it »

$x-- Post-decrement Returns $x, then decrements $x by one Try it »

PHP Logical Operators


The PHP logical operators are used to combine conditional statements.

Operator Name Example Result Try it

and And $x and $y True if both $x and $y are true Try it »

or Or $x or $y True if either $x or $y is true Try it »

xor Xor $x xor $y True if either $x or $y is true, Try it »


but not both

&& And $x && $y True if both $x and $y are true Try it »

|| Or $x || $y True if either $x or $y is true Try it »

! Not !$x True if $x is not true Try it »

PHP String Operators


Operator Name Example Result Try it

. Concatenation $txt1 . $txt2 Concatenation Try it »


of $txt1 and
$txt2

.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 Try it »


to $txt1

PHP has two operators that are specially designed for strings.
PHP Loops
Often when you write code, you want the same block of code to run over and over again a
certain number of times. So, instead of adding several almost equal code-lines in a script, we
can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition
is true.
In PHP, we have the following loop types:
• while - loops through a block of code as long as the specified condition is true
• do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
• for - loops through a block of code a specified number of times
• foreach - loops through a block of code for each element in an array

The PHP while Loop


The while loop executes a block of code as long as the specified condition is true.
Example
Print $i as long as $i is less than 6:

$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
The while loop does not run a specific number of times, but checks after each iteration if the
condition is still true.

The break Statement


With the break statement we can stop the loop even if the condition is still true:
Example
Stop the loop when $i is 3:

$i = 1;
while ($i < 6) {
if ($i == 3) break;
echo $i;
$i++;
}
OUTPUT: 12
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Stop, and jump to the next iteration if $i is 3:
<!DOCTYPE html>
<html>
<body>

<?php
$i = 0;

while ($i < 6) {


$i++;
if ($i == 3) continue;
echo $i;
}
?>

</body>
</html>

OUTPUT: 1245

Example
Count to 100 by tens:
$i = 0;
while ($i < 100) {
$i+=10;
echo $i "<br>";
}

The PHP do...while Loop


The do...while loop will always execute the block of code at least once, it will then check the
condition, and repeat the loop while the specified condition is true.
Example
Print $i as long as $i is less than 6:

$i = 1;

do {
echo $i;
$i++;
} while ($i < 6);
The PHP for Loop
The for loop is used when you know how many times the script should run.
Syntax
for (expression1, expression2, expression3) {
// code block
}
This is how it works:
• expression1 is evaluated once
• expression2 is evaluated before each iteration
• expression3 is evaluated after each iteration

Example
Print the numbers from 0 to 10:

for ($x = 0; $x <= 10; $x++) {


echo "The number is: $x <br>";
}

What is an Array?
An array is a special variable that can hold many values under a single name, and you can
access the values by referring to an index number or name.

PHP Array Types


In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays

Array Items
Array items can be of any data type.
The most common are strings and numbers (int, float), but array items can also be objects,
functions or even arrays.
You can have different data types in the same array.

Example
Array items of four different data types:
$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);

Indexed Arrays: These arrays use numeric indices. You can create an indexed array like
this:
$fruits = array("Apple", "Banana", "Cherry");
Associative Arrays: These arrays use named keys that you assign to them. They are
useful when you want to associate values with specific keys.
$ages = array("Alice" => 25, "Bob" => 30, "Charlie" => 35);

Multidimensional Arrays: These are arrays that contain one or more arrays. You can
think of them as arrays of arrays. They are often used to store data in a tabular format.
$contacts = array(
"John" => array("phone" => "123-4567", "email" => "[email protected]"),
"Jane" => array("phone" => "987-6543", "email" => "[email protected]")
);

STRING
A string is a sequence of characters, Strings in PHP are surrounded by either double quotation
marks, or single quotation marks.
Example
echo "Hello";
echo 'Hello';

String Length
The PHP strlen() function returns the length of a string.
Example
Return the length of the string "Hello world!":

echo strlen("Hello world!");

Word Count
The PHP str_word_count() function counts the number of words in a string.
Example
Count the number of word in the string "Hello world!":

echo str_word_count("Hello world!");

Search For Text Within a String


The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is
found, it will return FALSE.
Example
Search for the text "world" in the string "Hello world!":

echo strpos("Hello world!", "world");

PHP - Modify Strings


PHP has a set of built-in functions that you can use to modify strings.

1. Upper Case
Example
The strtoupper() function returns the string in upper case:

$x = "Hello World!";
echo strtoupper($x);

2. Lower Case
Example
The strtolower() function returns the string in lower case:

$x = "Hello World!";
echo strtolower($x);

3. Reverse a String
The PHP strrev() function reverses a string.
Example
Reverse the string "Hello World!":

$x = "Hello World!";
echo strrev($x);

4. String Concatenation
To concatenate, or combine, two strings you can use the . operator:
Example
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
You can add a space character like this:
Example
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
PHP Environment
A PHP environment refers to the software setup required for running PHP scripts. It typically
includes:
1. Web Server (e.g., Apache, Nginx) – to handle requests and serve PHP scripts.
2. PHP Interpreter – to execute PHP code.
3. Database (optional, e.g., MySQL, PostgreSQL) – if the PHP scripts require database
interaction.
The environment ensures that PHP scripts are processed and the output (e.g., HTML) is sent to the
user’s browser.
Components of a PHP Environment:
• Operating System (OS): Linux, Windows, macOS.
• Web Server: Serves the PHP script to the client (e.g., Apache or Nginx).
• PHP Engine: The interpreter that parses and runs PHP code.
• Database: Optional, for storing and retrieving data (e.g., MySQL, MariaDB).
• Development Tools: Tools like PHPStorm or Xdebug for debugging and development.
Popular PHP Environment Stacks:
• LAMP Stack (Linux, Apache, MySQL, PHP): A common setup for running PHP
applications on Linux.
• XAMPP/WAMP (Windows): For local development on Windows.
• MAMP (Mac): For local development on macOS.

Environment Variables in PHP


Environment variables are variables that are set in the operating system environment and can be
accessed in PHP to configure the application's behavior without hardcoding values into the codebase.
These variables can store information like database credentials, API keys, or paths to certain files, and
they are commonly used to manage configurations across different environments (development,
staging, production).
Accessing Environment Variables in PHP
PHP provides various ways to access environment variables:
1. $_ENV Superglobal: PHP automatically populates the $_ENV array with environment
variables set by the operating system or server.
echo $_ENV['USER']; // Prints the username of the logged-in user (if available).

2. getenv() Function: Retrieves the value of an environment variable directly.


echo getenv('DB_HOST'); // Retrieves the value of the DB_HOST variable.
3. putenv() Function: Allows you to set an environment variable during script execution.
putenv("APP_ENV=development");
Use Cases for Environment Variables:
• Database Connection Details: Storing database hostnames, usernames, passwords.
• API Keys: Keeping sensitive credentials outside the source code.
• Environment-specific Configurations: Switching between different environments (e.g.,
development, production).

Responding to http requests in php


In PHP, responding to HTTP requests involves understanding how to handle different types of HTTP
requests (e.g., GET, POST) and generating an appropriate response, which is often HTML but could
also be JSON, XML, or other formats.
Basic HTTP Request Handling in PHP
PHP scripts usually run on a web server (like Apache or Nginx) and are triggered when a request is
made to the server. Depending on the type of request, PHP can respond with different content.
1. Handling GET Requests
When a user sends data via the GET method (usually by entering a URL in the browser or clicking a
link), the data is passed in the URL’s query string.
PHP uses the $_GET superglobal to access this data.
<?php
// Example: http://example.com/index.php?name=John&age=25

if (isset($_GET['name']) && isset($_GET['age'])) {


$name = htmlspecialchars($_GET['name']); // Prevent XSS attacks
$age = (int) $_GET['age'];

echo "Hello, $name. You are $age years old.";


} else {
echo "Please provide your name and age.";
}
?>
• $_GET['name']: Fetches the value of the "name" parameter from the URL.

• htmlspecialchars(): Used to avoid Cross-Site Scripting (XSS) attacks.


2. Handling POST Requests
A POST request is typically used when submitting data through forms. Data sent via POST is not
visible in the URL, making it more secure for sensitive data like passwords.
PHP uses the $_POST superglobal to access this data.
<!-- HTML Form -->
<form action="index.php" method="POST">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit" value="Submit">
</form>

<!-- PHP Script to Handle POST Request -->


<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = htmlspecialchars($_POST['name']);
$age = (int) $_POST['age'];

echo "Thank you, $name. You are $age years old.";


}
?>
• $_POST['name']: Fetches the value of the "name" field from the form.

• $_SERVER['REQUEST_METHOD']: Checks the type of HTTP request (GET, POST, etc.).


3. Handling Other HTTP Methods (PUT, DELETE)
While GET and POST are most commonly used in web forms, PHP can also handle other HTTP
methods such as PUT and DELETE, especially in RESTful APIs.
To handle these methods, PHP reads the request body:
<?php
// Handling PUT and DELETE methods
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
parse_str(file_get_contents("php://input"), $put_vars);
echo "Handling PUT Request";
print_r($put_vars); // Access PUT data
} elseif ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
echo "Handling DELETE Request";
}
?>
• file_get_contents("php://input"): Reads the raw data from the request body.

Responding with JSON


For APIs, PHP often responds with JSON instead of HTML. This can be done using json_encode().
<?php
header('Content-Type: application/json');

// Example of sending a JSON response


$data = [
'status' => 'success',
'message' => 'Hello, this is a JSON response!',
];

echo json_encode($data);
?>
• header('Content-Type: application/json'): Sets the Content-Type header to application/json,
indicating the response is JSON.
• json_encode(): Converts an array or object to JSON format.
HTTP Status Codes in PHP
PHP allows you to send custom HTTP status codes along with responses. For example:
<?php
http_response_code(404);
echo "Page not found!";
?>
• http_response_code(): Sets the HTTP status code (e.g., 404 for Not Found, 200 for OK).

Redirecting HTTP Requests


You can redirect users to a different page using the Location header.
<?php
header('Location: http://example.com/newpage.php');
exit; // Always call exit() after a redirect to stop further script execution
?>
Summary
1. GET Requests: Use $_GET to access query parameters sent in the URL.
2. POST Requests: Use $_POST to handle form submissions or sensitive data.
3. Other Methods: Use php://input to handle PUT, DELETE, etc.
4. JSON Response: Use json_encode() to return JSON data, commonly used in APIs.
5. HTTP Status Codes: Use http_response_code() to set the appropriate response code.
6. Redirects: Use the Location header to redirect users to another URL.

PHP Files
In PHP, file handling is a fundamental aspect that allows you to create, open, read, write, and manage
files on the server. This capability is crucial for many web applications, such as storing logs, user
uploads, or generating dynamic content. Below is an overview of key file operations in PHP, along
with commonly used functions and examples.
1. Basic File Handling Functions
File Opening and Closing:
• fopen($filename, $mode): Opens a file in a specified mode. Returns a file pointer resource
on success or false on failure.
• fclose($filePointer): Closes an open file pointer.
File Modes:
• "r": Read-only. Starts at the beginning of the file.
• "r+": Read/Write. Starts at the beginning of the file.
• "w": Write-only. Truncates the file to zero length or creates a new file if it doesn't exist.
• "w+": Read/Write. Truncates the file to zero length or creates a new file.
• "a": Write-only. Starts at the end of the file or creates a new file.
• "a+": Read/Write. Starts at the end of the file.
• "x": Write-only. Creates a new file. Returns false if the file exists.
• "x+": Read/Write. Creates a new file. Returns false if the file exists

Reading from a File in PHP


Steps for Reading a File:
1. Open the File:
o Use the fopen() function to open the file in read mode ("r").
$file = fopen("example.txt", "r");
2. Read the File:
o You can use different functions depending on how you want to read the file:
▪ fread(): Reads a specified number of bytes from the file.
▪ fgets(): Reads a single line from the file.
▪ file_get_contents(): Reads the entire file into a string.
// Using fgets() to read line by line
while (!feof($file)) { // Check if the end of file has been reached
$line = fgets($file); // Read a line from the file
echo $line . "<br>";
}
3. Close the File:
o Use the fclose() function to close the file and free up resources.
fclose($file);
Example - Reading Entire File Content:
$content = file_get_contents("example.txt");
echo $content;
2. Writing to a File in PHP
Steps for Writing to a File:
1. Open the File:
o Use the fopen() function with the appropriate mode:
▪ "w": Write mode. This will erase the existing content and start fresh.
▪ "a": Append mode. This will add data to the end of the file.
$file = fopen("example.txt", "w");
2. Write to the File:
o Use the fwrite() function to write data to the file.
$text = "Hello, World!\n";
fwrite($file, $text);
o file_put_contents(): You can also use this function to write data directly to a file. If
the file does not exist, it will create one.
file_put_contents("example.txt", "Hello, World!\n");
3. Close the File:
o Always close the file using the fclose() function after you are done writing.
fclose($file);
Example - Appending to a File:
$file = fopen("example.txt", "a"); // Open in append mode
fwrite($file, "Appending this text to the file.\n");
fclose($file);

Cookies in PHP
Cookies are small pieces of data stored on the client’s browser, which can be used to remember
information about the user across different pages or sessions.
Setting a Cookie
To set a cookie in PHP, use the setcookie() function:
setcookie("username", "JohnDoe", time() + (86400 * 30), "/");
// Parameters: (name, value, expiry_time, path)
• name: The name of the cookie.
• value: The value of the cookie.
• expiry_time: The expiration time (in seconds). time() + (86400 * 30) sets the cookie to
expire in 30 days.
• path: The path on the server in which the cookie will be available.
Retrieving a Cookie
To retrieve a cookie, use the $_COOKIE superglobal array:
if(isset($_COOKIE["username"])) {
echo "Username is: " . $_COOKIE["username"];
} else {
echo "Cookie is not set.";
}
Deleting a Cookie
To delete a cookie, set its expiration time to a past date:
setcookie("username", "", time() - 3600, "/");

Sessions in PHP
Sessions are a way to store information across multiple pages of a website, but unlike cookies, the
data is stored on the server. PHP assigns a unique session ID to the client, which is then used to access
the stored data on the server.
Starting a Session
To start a session, use the session_start() function. It should be called at the beginning of the script
before any output is sent to the browser.
session_start();
Storing and Retrieving Session Variables
Session variables are stored in the $_SESSION superglobal array.
// Storing session variables
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "[email protected]";

// Retrieving session variables


echo $_SESSION["username"]; // Outputs: JohnDoe
Destroying a Session
To delete all session variables and destroy the session, use session_unset() and session_destroy().
session_unset();
session_destroy();

Difference Between Sessions and Cookies


• Storage Location:
o Cookies: Data is stored on the client-side (browser).
o Sessions: Data is stored on the server-side.
• Security:
o Cookies: Less secure, as they are stored on the client-side and can be accessed or
manipulated by users.
o Sessions: More secure, as data is stored on the server and only a session ID is shared
with the client.
• Lifetime:
o Cookies: Can persist for a long duration based on the expiration time set.
o Sessions: Typically last until the browser is closed or the session is explicitly
destroyed.
When to Use Each?
• Use Cookies:
o When you need to store small amounts of data that should persist between sessions,
such as user preferences or login status.
o When the data is not sensitive.
• Use Sessions:
o When you need to store sensitive or temporary data, such as user authentication status
or shopping cart contents.
o When security is a concern, as session data is stored on the server.

You might also like