[go: up one dir, main page]

0% found this document useful (0 votes)
8 views28 pages

unit-4webost

This document provides an overview of PHP basics, including how to use PHP, variable types, operators, flow control structures, and functions. It covers essential topics such as including files, conditional statements, loops, and event-driven programming. Additionally, it highlights built-in PHP libraries for text manipulation, mathematical operations, and date/time handling.

Uploaded by

Swathi Shakanaz
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)
8 views28 pages

unit-4webost

This document provides an overview of PHP basics, including how to use PHP, variable types, operators, flow control structures, and functions. It covers essential topics such as including files, conditional statements, loops, and event-driven programming. Additionally, it highlights built-in PHP libraries for text manipulation, mathematical operations, and date/time handling.

Uploaded by

Swathi Shakanaz
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/ 28

Unit- 4

Understanding PHP: Basics and Flow


Control
1. How to Use PHP
PHP is a server-side scripting language used to develop dynamic web applications.
A basic PHP script is enclosed within <?php ... ?> tags and is processed on the server.

Example: Hello World in PHP


<?php
echo "Hello, World!";
?>

✅ This prints "Hello, World!" on the webpage.

2. PHP Variables
PHP variables store data and start with a $ symbol. Variable names are case-sensitive.

Variable Declaration
$name = "John";
$age = 25;
$is_logged_in = true;

Variable Types

 String: $name = "John";


 Integer: $age = 25;
 Float: $price = 10.5;
 Boolean: $is_logged_in = true;
 Array: $colors = ["Red", "Green", "Blue"];
 Object: class Car {}

Variable Scope
$x = 10; // Global variable

function test() {
global $x; // Access global variable inside function
echo $x;
}
test();

3. Operators in PHP
Operators in PHP allow you to perform mathematical, comparison, logical, and other
operations on variables and values.

1. Arithmetic Operators
Used for mathematical calculations.

Operator Description Example Result


+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 3 * 4 12
/ Division 10 / 2 5
% Modulus (Remainder) 10 % 3 1
** Exponentiation 2 ** 3 8

Example
$x = 10;
$y = 3;

echo $x + $y; // 13
echo $x - $y; // 7
echo $x * $y; // 30
echo $x / $y; // 3.33
echo $x % $y; // 1
echo $x ** $y; // 1000

2. Assignment Operators
Used to assign values to variables.

Operator Description Example Equivalent To


= Assign $x = 10; $x = 10;
+= Add and assign $x += 5; $x = $x + 5;
-= Subtract and assign $x -= 2; $x = $x - 2;
*= Multiply and assign $x *= 3; $x = $x * 3;
/= Divide and assign $x /= 2; $x = $x / 2;
Operator Description Example Equivalent To
%= Modulus and assign $x %= 3; $x = $x % 3;

Example
$x = 10;
$x += 5; // $x = $x + 5 (15)
$x -= 3; // $x = $x - 3 (12)
$x *= 2; // $x = $x * 2 (24)
$x /= 4; // $x = $x / 4 (6)
$x %= 5; // $x = $x % 5 (1)

echo $x; // Output: 1

3. Comparison Operators
Used to compare values and return true (1) or false (0).

Operator Description Example Result


== Equal 5 == "5" true
=== Identical (Equal & Same Type) 5 === "5" false
!= Not Equal 5 != 10 true
<> Not Equal 5 <> 10 true
!== Not Identical 5 !== "5" true
> Greater Than 10 > 5 true
< Less Than 5 < 10 true
>= Greater Than or Equal 10 >= 10 true
<= Less Than or Equal 5 <= 5 true

Example
$a = 5;
$b = "5";

echo ($a == $b); // true (values are equal)


echo ($a === $b); // false (types are different)
echo ($a != 10); // true
echo ($a > 3); // true
echo ($a < 2); // false

4. Logical Operators
Used to combine conditional statements.

Operator Description Example Result


&& AND (Both must be true) true && false false
Operator Description Example Result
and AND (Lower precedence) true and false false
` ` OR (At least one must be true)
or OR (Lower precedence) true or false true
! NOT (Reverses condition) !true false
xor XOR (Only one must be true) true xor true false

Example
$logged_in = true;
$is_admin = false;

if ($logged_in && $is_admin) {


echo "Welcome, Admin!";
} else {
echo "Access Denied.";
}

// Output: Access Denied.

5. Increment & Decrement Operators


Used to increase or decrease values by 1.

Operator Description Example Equivalent To


++$x Pre-increment ++$x; $x = $x + 1;
$x++ Post-increment $x++; $x = $x + 1;
--$x Pre-decrement --$x; $x = $x - 1;
$x-- Post-decrement $x--; $x = $x - 1;

Example
$x = 5;
echo ++$x; // Pre-increment (6)
echo $x++; // Post-increment (6, then $x becomes 7)
echo --$x; // Pre-decrement (6)
echo $x--; // Post-decrement (6, then $x becomes 5)

6. String Operators
Used for string manipulation.

Operator Description Example Result


. Concatenation "Hello " . "World" "Hello World"
.= Concatenation Assignment $x .= " World"; $x = $x . " World";
Example
$a = "Hello";
$b = " World";

echo $a . $b; // Output: Hello World

$a .= " PHP"; // $a = $a . " PHP";


echo $a; // Output: Hello PHP

7. Ternary Operator
A shorthand for if-else.

php
CopyEdit
$age = 18;
echo ($age >= 18) ? "Adult" : "Minor";

✅ Output: "Adult"

8. Null Coalescing Operator (??)


Used to check if a variable exists and is not null.

$username = $_GET['user'] ?? 'Guest';


echo $username; // If 'user' is not set, it outputs "Guest".

9. Spaceship Operator (<=>)


Used for sorting and comparisons.

Expression Result

5 <=> 10 -1 (Left is smaller)

10 <=> 10 0 (Equal)
15 <=> 10 1 (Left is greater)

Example
echo 5 <=> 10; // -1
echo 10 <=> 10; // 0
echo 15 <=> 10; // 1
Conclusion
PHP operators allow efficient handling of mathematical, logical, and comparison
operations.

4. Including Files in PHP


PHP allows including other files using:

 include "file.php";
 require "file.php"; (Stops script on failure)

Example: Including a Header


include "header.php";
echo "Welcome to my website!";

Flow Control in PHP


Flow control structures determine the execution flow of a PHP script based on conditions and
loops.

1. Conditional Statements
Conditional statements allow a script to make decisions based on conditions.

1.1 If Statement

Executes code only if a condition is true.

$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}

1.2 If-Else Statement

Executes one block if a condition is true, otherwise executes another block.

$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}

✅ Output: "You are a minor."

1.3 If-ElseIf-Else Statement

Allows checking multiple conditions.

$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}

✅ Output: "Grade: B"

1.4 Ternary Operator (? :)

A shorter version of if-else.

$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";

✅ Output: "Adult"

1.5 Null Coalescing Operator (??)

Checks if a variable is set; otherwise, assigns a default value.

$username = $_GET['user'] ?? 'Guest';


echo $username;

✅ If $_GET['user'] is not set, "Guest" is printed.

1.6 Switch Statement

Used when checking multiple values for a variable.


$day = "Monday";

switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is coming!";
break;
case "Sunday":
echo "It's a holiday!";
break;
default:
echo "It's a regular day.";
}

✅ Output: "Start of the week!"

2. Loops in PHP
Loops allow executing a block of code multiple times.

2.1 For Loop

Used when the number of iterations is known.

for ($i = 1; $i <= 5; $i++) {


echo "Number: $i <br>";
}

✅ Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

2.2 While Loop

Used when condition-based iteration is required.

$x = 1;
while ($x <= 5) {
echo "Count: $x <br>";
$x++;
}
✅ Output is the same as the for loop.

2.3 Do-While Loop

Similar to while, but runs at least once.

$x = 10;
do {
echo "Value: $x <br>";
$x++;
} while ($x <= 5);

✅ Output: "Value: 10" (Runs once before condition fails.)

2.4 Foreach Loop (For Arrays)

Used to iterate over arrays.

$colors = ["Red", "Green", "Blue"];


foreach ($colors as $color) {
echo "Color: $color <br>";
}

✅ Output:

less
CopyEdit
Color: Red
Color: Green
Color: Blue

3. Break and Continue in Loops


3.1 Break Statement

Stops a loop immediately.

for ($i = 1; $i <= 10; $i++) {


if ($i == 5) {
break; // Stops at 5
}
echo "$i ";
}

✅ Output: "1 2 3 4"


3.2 Continue Statement

Skips the current iteration and moves to the next.

for ($i = 1; $i <= 5; $i++) {


if ($i == 3) {
continue; // Skips 3
}
echo "$i ";
}

✅ Output: "1 2 4 5"

4. Nested Loops and Conditional Statements


Loops and conditions can be nested inside each other.

Example: Nested For Loop


for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "($i, $j) ";
}
echo "<br>";
}

✅ Output:

(1,1) (1,2) (1,3)


(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

5. Goto Statement (Rarely Used)


Jumps execution to a label. Avoid using it unless necessary.

$x = 5;
if ($x == 5) {
goto end;
}
echo "This will never be printed.";

end:
echo "Jumped here!";

✅ Output: "Jumped here!"


7. Creating Your Own PHP Functions
Functions are blocks of reusable code.

Defining and Calling a Function


function greet($name) {
return "Hello, $name!";
}

echo greet("Alice");

Default Parameters
function greet($name = "Guest") {
return "Hello, $name!";
}

echo greet(); // "Hello, Guest!"

Returning Values
function add($a, $b) {
return $a + $b;
}

$result = add(5, 10);


echo $result; // 15

8. Event-Driven PHP
PHP is not inherently event-driven, but you can implement event-driven behavior using
JavaScript or frameworks like Laravel, Symfony.

Basic Event Handling in PHP

 Using Form Submissions


 Using AJAX with JavaScript
 Using WebSockets for real-time events

Example: Form Handling (User Click Event)


<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Button Clicked!";
}
?>

<form method="post">
<button type="submit">Click Me</button>
</form>
Example: Event Handling with JavaScript and PHP (AJAX)
// JavaScript (AJAX Request)
document.getElementById("btn").addEventListener("click", function() {
fetch("server.php")
.then(response => response.text())
.then(data => alert(data));
});

// PHP (server.php)
<?php
echo "Button Clicked!";
?>

9. Summary
Topic Description
PHP Basics PHP scripts use <?php ... ?> tags
Variables Store data ($name = "John";)
Operators Perform calculations (+, -, *, /)
Including Files Use include or require
Flow Control Use if-else, switch, for, while
Functions Create reusable code blocks (function myFunc() {})
Loops for, while, foreach for repeated tasks
Event-Driven PHP Use form submissions, JavaScript AJAX

PHP Libraries: Essential Built-in Functions


PHP comes with many built-in libraries to handle text, math, date/time, and images. Below
is a breakdown of commonly used functions.

1. Text Functions (String Manipulation)


PHP provides a rich set of functions to manipulate text.

Basic String Operations


$str = "Hello World";

echo strlen($str); // 11 (Length of string)


echo str_word_count($str); // 2 (Number of words)
echo strrev($str); // "dlroW olleH" (Reverses the string)
echo strpos($str, "World"); // 6 (Finds position of substring)
echo str_replace("World", "PHP", $str); // "Hello PHP"

String Case Manipulation


echo strtoupper("hello"); // "HELLO"
echo strtolower("HELLO"); // "hello"
echo ucfirst("hello"); // "Hello" (First letter capitalized)
echo ucwords("hello world"); // "Hello World" (Capitalize each word)

Substring & Trimming


echo substr("abcdef", 2, 3); // "cde" (Extracts substring)
echo trim(" Hello "); // "Hello" (Removes spaces)
echo ltrim(" Hello"); // "Hello" (Left trim)
echo rtrim("Hello "); // "Hello" (Right trim)

2. Math Functions
PHP has a variety of functions for mathematical operations.

Basic Math Operations


echo abs(-10); // 10 (Absolute value)
echo pow(2, 3); // 8 (2^3)
echo sqrt(16); // 4 (Square root)
echo round(4.7); // 5 (Rounds to nearest integer)
echo ceil(4.2); // 5 (Rounds up)
echo floor(4.8); // 4 (Rounds down)

Random Numbers
echo rand(); // Generates a random number
echo rand(1, 100); // Random number between 1 and 100

Trigonometry
echo sin(deg2rad(30)); // 0.5 (Sine of 30 degrees)
echo cos(deg2rad(60)); // 0.5 (Cosine of 60 degrees)
echo tan(deg2rad(45)); // 1 (Tangent of 45 degrees)

3. Date and Time Functions


Handling dates and times is crucial in PHP.

Getting the Current Date/Time


echo date("Y-m-d"); // 2025-02-18 (Current date)
echo date("H:i:s"); // 14:35:20 (Current time)
echo date("l"); // "Tuesday" (Day of the week)

Formatting Dates
echo date("d-m-Y", strtotime("2025-12-31")); // 31-12-2025
echo date("F j, Y", strtotime("next Friday")); // "February 23, 2025"

Timestamps & Timezones


echo time(); // Unix timestamp (Seconds since Jan 1, 1970)
date_default_timezone_set("America/New_York");
echo date("Y-m-d H:i:s"); // Shows current time in New York

4. Image-Handling Functions (GD Library)


PHP’s GD library allows creating and manipulating images dynamically.

Check GD Library
if (extension_loaded('gd') && function_exists('gd_info')) {
echo "GD is installed!";
} else {
echo "GD is not installed!";
}

Creating an Image
header("Content-Type: image/png"); // Set output type

$image = imagecreatetruecolor(200, 100); // Create an image canvas


$bgColor = imagecolorallocate($image, 0, 102, 204); // Define color
$textColor = imagecolorallocate($image, 255, 255, 255); // White text

imagefilledrectangle($image, 0, 0, 200, 100, $bgColor); // Fill background


imagestring($image, 5, 50, 40, "Hello!", $textColor); // Add text

imagepng($image); // Output image


imagedestroy($image); // Free memory

Resizing an Image
$source = imagecreatefromjpeg("image.jpg");
$resized = imagescale($source, 100, 100); // Resize to 100x100
imagejpeg($resized, "resized.jpg"); // Save new image
imagedestroy($source);
imagedestroy($resized);

Conclusion
 Text functions: String manipulation (strlen(), str_replace(), substr())
 Math functions: Numeric calculations (abs(), pow(), sqrt())
 Date/Time functions: Formatting and time zones (date(), strtotime())
 Image functions: Create/edit images (imagecreatetruecolor(), imagejpeg())

PHP Security: Common Vulnerabilities &


Solutions
PHP applications are often targeted by attackers due to poor security practices. Below are
common vulnerabilities and best practices to secure PHP applications.

1. SQL Injection (SQLi)


� Vulnerability

When user input is not sanitized before being used in SQL queries, attackers can manipulate
the database.

� Insecure Code
$userid = $_GET['id'];
$query = "SELECT * FROM users WHERE id = '$userid'";
$result = mysqli_query($conn, $query);

✅ If a user enters 1 OR 1=1, it retrieves all users!

� Solution: Use Prepared Statements (PDO or MySQLi)


$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $_GET['id']); // Bind integer parameter
$stmt->execute();
$result = $stmt->get_result();

✅ Prevents SQL Injection by treating input as a value, not SQL code.

2. Cross-Site Scripting (XSS)


� Vulnerability

XSS occurs when attackers inject malicious JavaScript into web pages, which is then
executed in users' browsers.
� Insecure Code
echo "Welcome, " . $_GET['name']; // Directly outputting user input

✅ If name=<script>alert('Hacked!')</script>, the script executes!

� Solution: Escape Output (htmlspecialchars())


echo "Welcome, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');

✅ Converts <script> into safe text, preventing execution.

3. Cross-Site Request Forgery (CSRF)


� Vulnerability

CSRF tricks users into performing unwanted actions (e.g., submitting a form) while logged
in.

� Insecure Code (No CSRF Protection)

A logged-in user could unknowingly submit a form by visiting a malicious link.

� Solution: Use CSRF Tokens

Generate a unique token and validate it in forms:

// Generate CSRF token


session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Check CSRF token in form submission


if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die("CSRF validation failed!");
}
}

✅ Prevents unauthorized form submissions.

4. Remote Code Execution (RCE)


� Vulnerability
RCE allows attackers to execute arbitrary commands on the server.

� Insecure Code (eval(), system(), exec())


$cmd = $_GET['cmd'];
eval($cmd); // Executes user input

✅ An attacker can run ?cmd=system('rm -rf /');

� Solution: Disable Dangerous Functions & Validate Input

 Disable dangerous functions in php.ini:

disable_functions = exec, shell_exec, system, passthru, proc_open,


eval

 Validate user input:

if (!preg_match('/^[a-zA-Z0-9]+$/', $_GET['cmd'])) {
die("Invalid command!");
}

✅ Prevents unauthorized command execution.

5. File Upload Vulnerabilities


� Vulnerability

Uploading malicious scripts disguised as images (shell.php.jpg) can lead to Remote File
Inclusion (RFI).

� Insecure Code
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" .
$_FILES["file"]["name"]);

✅ Attackers can upload shell.php and execute it.

� Solution: Validate File Type & Use Secure Folder


$allowed_types = ['jpg', 'png', 'gif']; // Allowed extensions
$file_ext = strtolower(pathinfo($_FILES["file"]["name"],
PATHINFO_EXTENSION));

if (!in_array($file_ext, $allowed_types)) {
die("Invalid file type!");
}

$upload_dir = "uploads/";
$new_name = uniqid() . "." . $file_ext; // Rename file
move_uploaded_file($_FILES["file"]["tmp_name"], $upload_dir . $new_name);

✅ Prevents execution of malicious scripts.

6. Session Hijacking & Fixation


� Vulnerability

Attackers steal session IDs to impersonate users.

� Insecure Code (No Regeneration)


session_start();

✅ If an attacker gets the PHPSESSID, they can hijack the session.

� Solution: Regenerate & Secure Cookies


session_start();
session_regenerate_id(true); // Regenerate session ID
ini_set('session.cookie_httponly', 1); // Prevent JavaScript access
ini_set('session.cookie_secure', 1); // Use only HTTPS

✅ Reduces session hijacking risks.

7. Directory Traversal
� Vulnerability

Allows attackers to access system files (../../etc/passwd).

� Insecure Code
$file = $_GET['file'];
include "uploads/" . $file;

✅ ?file=../../etc/passwd exposes sensitive system files!

� Solution: Validate File Names


$allowed_files = ['profile.jpg', 'report.pdf'];
if (!in_array($_GET['file'], $allowed_files)) {
die("Access denied!");
}

✅ Prevents unauthorized file access.


8. Exposing Sensitive Information
� Vulnerability

Error messages can leak database credentials.

� Insecure Code
mysqli_connect("localhost", "root", "password", "mydb") or
die(mysqli_error());

✅ If connection fails, error messages expose details.

� Solution: Disable Errors in Production


error_reporting(0);
ini_set('display_errors', 0);

✅ Hides sensitive error messages.

9. Using Weak Password Hashing


� Vulnerability

Storing passwords as plaintext is dangerous.

� Insecure Code
$hashed = md5($password); // Weak hashing

✅ MD5 & SHA1 are easily cracked.

� Solution: Use password_hash()


$hashed = password_hash($password, PASSWORD_BCRYPT);
if (password_verify($password, $hashed)) {
echo "Valid login!";
}

✅ Secure password storage.

10. Keeping PHP & Dependencies Updated


� Vulnerability

Using outdated PHP versions exposes security flaws.

� Solution

 Always use supported PHP versions (php -v)


 Regularly update frameworks, libraries, and dependencies
 Monitor for security patches (e.g., via composer audit)

Conclusion
Vulnerability Solution
SQL Injection (SQLi) Use prepared statements (PDO/MySQLi)
Cross-Site Scripting (XSS) Escape output with htmlspecialchars()
Cross-Site Request Forgery (CSRF) Use CSRF tokens
Remote Code Execution (RCE) Disable eval() & validate input
File Upload Risks Check file types & rename uploads
Session Hijacking Use session_regenerate_id()
Directory Traversal Validate file paths
Sensitive Data Exposure Disable error messages in production
Weak Passwords Use password_hash()
Outdated Software Keep PHP & libraries updated

Object-Oriented Programming (OOP) in PHP


OOP in PHP allows you to structure your code into reusable classes and objects, making it
more maintainable and scalable. Here’s a breakdown of the basics:

1. Basics of OOP in PHP


OOP is based on the following concepts:

 Classes & Objects → Blueprint (class) and instance (object)


 Properties → Variables inside a class
 Methods → Functions inside a class
 Encapsulation → Controlling access with public, private, protected
 Inheritance → Extending classes
 Polymorphism → Method overriding

2. Creating a Class and Object


A class is a template, and an object is an instance of that class.

Defining a Class
class Car {
public $brand; // Property

// Constructor method (called automatically)


public function __construct($brand) {
$this->brand = $brand;
}

// Method
public function getBrand() {
return "This car is a " . $this->brand;
}
}

Creating an Object
$myCar = new Car("Toyota");
echo $myCar->getBrand(); // Output: This car is a Toyota

3. Class Methods
A method is a function inside a class.

Example: Methods with Parameters


class MathOperations {
public function add($a, $b) {
return $a + $b;
}
}

$math = new MathOperations();


echo $math->add(5, 10); // Output: 15

Method Visibility: public, private, protected

 public → Accessible everywhere


 private → Accessible only inside the class
 protected → Accessible inside the class & subclasses
class Example {
public $publicVar = "Public";
private $privateVar = "Private";
protected $protectedVar = "Protected";

public function showPrivate() {


return $this->privateVar; // Accessible inside the class
}
}

$obj = new Example();


echo $obj->publicVar; // ✅ Allowed
// echo $obj->privateVar; ✅ Error
// echo $obj->protectedVar; ✅ Error
echo $obj->showPrivate(); // ✅ Allowed (via method)

4. Loading Classes (Autoloading)


Manually including classes using require or include can be tedious. Instead, use
autoloading:

Using spl_autoload_register()
spl_autoload_register(function ($class) {
include $class . "."; // Assumes file name = class name
});

$obj = new Car("BMW"); // will automatically load Car.

5. Extending a Class (Inheritance)


Inheritance allows a class to use methods from another class.

Example: Parent & Child Classes

class Vehicle {
protected $type = "Unknown";

public function getType() {


return $this->type;
}
}

class Car extends Vehicle {


public function __construct() {
$this->type = "Car"; // Override parent property
}
}

$car = new Car();


echo $car->getType(); // Output: Car
Method Overriding

class ParentClass {
public function greet() {
return "Hello from Parent!";
}
}

class ChildClass extends ParentClass {


public function greet() {
return "Hello from Child!";
}
}

$obj = new ChildClass();


echo $obj->greet(); // Output: Hello from Child!

Conclusion
 Classes define objects with properties and methods.
 Objects are created from classes.
 Encapsulation controls data access (public, private, protected).
 Autoloading helps automatically load class files.
 Inheritance allows code reuse between classes.

PHP : Sessions, Cookies, and Shopping


carts
In PHP, sessions and cookies allow data to persist across different pages. These are widely
used in e-commerce websites to manage user logins and shopping carts.

1. Persistent Data in
What is Persistent Data?
Persistent data refers to data that remains available between page reloads or across
multiple pages. provides several ways to store persistent data:

 Sessions (Stored on the server)


 Cookies (Stored on the user's browser)
 Database Storage (For long-term storage)

2. Sessions
What is a Session?

A session stores user data (e.g., login info, cart items) on the server and assigns a unique
session_id to the user.

Starting a Session

session_start(); // Starts a session


$_SESSION['username'] = "JohnDoe"; // Store data
echo $_SESSION['username']; // Retrieve data

Destroying a Session (Logout)

session_start();
session_destroy(); // Destroys the session
unset($_SESSION['username']); // Remove specific session data

3. Cookies
What is a Cookie?

A cookie is a small piece of data stored on the user's browser and sent to the server with
each request.

Creating a Cookie

setcookie("user", "JohnDoe", time() + (86400 * 7), "/"); // Cookie lasts 7


days

Retrieving a Cookie

if(isset($_COOKIE['user'])) {
echo "Hello, " . $_COOKIE['user'];
}

Deleting a Cookie

setcookie("user", "", time() - 3600, "/"); // Set expiration to past

4. Shopping Cart in
A shopping cart allows users to add and remove products before checkout. Sessions are
commonly used to store cart data.

Step 1: Add Products to Cart

session_start();

if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = []; // Initialize empty cart
}

$product_id = $_GET['id']; // Get product ID from URL


$quantity = 1; // Default quantity

// Add product to session cart


if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id] += $quantity; // Update quantity
} else {
$_SESSION['cart'][$product_id] = $quantity; // Add new product
}

echo "Product added to cart!";

Step 2: Display Cart Items

session_start();

if (!empty($_SESSION['cart'])) {
echo "<h2>Your Shopping Cart</h2>";
foreach ($_SESSION['cart'] as $id => $qty) {
echo "Product ID: $id - Quantity: $qty <br>";
}
} else {
echo "Your cart is empty.";
}

Step 3: Remove Items from Cart

session_start();
$product_id = $_GET['id'];

if (isset($_SESSION['cart'][$product_id])) {
unset($_SESSION['cart'][$product_id]); // Remove item
}

echo "Product removed!";

Step 4: Clear the Cart (Empty Cart)

session_start();
$_SESSION['cart'] = []; // Reset the cart
echo "Cart cleared!";

5. Storing Cart Data in Cookies (Alternative)


If you want the cart to persist even after the session ends, you can store it in a cookie.

Saving Cart Data in a Cookie

$cart_data = json_encode($_SESSION['cart']); // Convert array to JSON


setcookie("cart", $cart_data, time() + (86400 * 7), "/"); // Store for 7
days

Retrieving Cart Data from a Cookie

if (isset($_COOKIE['cart'])) {
$_SESSION['cart'] = json_decode($_COOKIE['cart'], true);
}

6. Shopping Cart with Database Storage


Instead of storing cart data in sessions or cookies, we can store it in a database.

Create a cart Table


sql

CREATE TABLE cart (


id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Add Product to Cart (Database)

$conn = new mysqli("localhost", "root", "", "shop");

$user_id = 1; // Assume user is logged in


$product_id = $_GET['id'];
$quantity = 1;

// Insert or update product in cart


$sql = "INSERT INTO cart (user_id, product_id, quantity)
VALUES ($user_id, $product_id, $quantity)
ON DUPLICATE KEY UPDATE quantity = quantity + 1";
$conn->query($sql);

Retrieve Cart Items from Database

$sql = "SELECT * FROM cart WHERE user_id = 1";


$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {


echo "Product ID: " . $row['product_id'] . " - Quantity: " .
$row['quantity'] . "<br>";
}

7. Best Practices for Sessions and Carts


✅ Use Sessions for Temporary Data: Store cart items in $_SESSION, but clear them after
checkout.
✅ Use Cookies for Remembering Users: Store user preferences in cookies, but avoid
storing sensitive data.
✅ Sanitize User Input: Always validate and escape user inputs to prevent attacks (SQL
Injection, XSS).
✅ Secure Session Data:

 Use session_regenerate_id(true); to prevent session fixation.


 Store session data securely using ini_set('session.cookie_httponly', 1);
✅ Use Database for Permanent Cart Storage: If users should keep items after
logout, store cart items in a database.

Conclusion

 Sessions are best for temporary cart storage.


 Cookies are useful for remembering user preferences.
 Database storage ensures cart persistence across logins.
 Security is important (input validation, session protection).

You might also like