IT219 Web Programming II

Web Programming IIUnit 613 min read

PHP Cookies, Sessions & Security: Storage, State & Protection

Unit 6 of Web Programming II: Explores how PHP maintains user state via cookies/sessions, secures data transmission, and defends against attacks like XSS/SQLi, with hands-on examples of validation, encryption, and real-world security practices.

TAKEAWAYS:

  • Learn how cookies and sessions store client-side and server-side data, respectively, and their trade-offs.
  • Master session management (start, destroy, variables) with PHP’s session_start() and $_SESSION superglobal.
  • Understand security threats (XSS, CSRF, SQLi) and PHP’s built-in defenses (e.g., filter_input(), mysqli_real_escape_string()).
  • Implement input validation and output encoding to prevent injection attacks.
  • Compare cookies vs. sessions in a table with use cases (e.g., shopping carts vs. login tokens).
  • Write secure PHP code using hashing (password_hash()) and HTTPS for encrypted data.

1. Cookies: Client-Side Data Storage

Cookies are small text files stored in the user’s browser. They persist between sessions and are sent with every HTTP request to the server.

How Cookies Work

  1. Server sends a cookie via Set-Cookie header:
    Set-Cookie: user_id=12345; expires=Wed, 21 Oct 2025 07:28:00 GMT; path=/
    
  2. Browser stores it and includes it in subsequent requests:
    GET /profile.php HTTP/1.1
    Cookie: user_id=12345
    
Function Purpose
setcookie() Creates a cookie (must be called before <?php or header() is sent).
$_COOKIE Superglobal array to read cookies.
isset($_COOKIE['key']) Checks if a cookie exists.
flowchart TD
    A["User visits site"] --> B["PHP: setcookie('theme', 'dark')"]
    B --> C["Browser stores cookie"]
    C --> D["User returns: _COOKIE['theme'] = 'dark'"]
    D --> E["PHP applies dark theme"]

Code Example:

<?php
// Set cookie (must run before output)
setcookie("theme", "dark", time() + 86400, "/"); // Expires in 1 day

// Retrieve cookie
if (isset($_COOKIE["theme"])) {
    echo "Current theme: " . htmlspecialchars($_COOKIE["theme"]);
}
?>

Trace Table:

Step Action Cookie State ($_COOKIE)
1 setcookie() called theme → "dark" (expires in 1 day)
2 User reloads page theme persists in browser
3 isset() checks cookie Returns true; displays "dark"

2. Sessions: Server-Side State Management

Sessions store data on the server and assign a unique session ID to the user’s browser via a cookie.

How Sessions Work

  1. Server starts a session (session_start()).
  2. Assigns a session ID (stored in a cookie).
  3. Data is stored in $_SESSION superglobal.

PHP Session Lifecycle

sequenceDiagram
  participant User
  participant Browser
  participant Server
  User->>Browser: Visits site
  Browser->>Server: HTTP request
  Server->>Server: session_start()
  Server->>Browser: Set-Cookie (session_id=abc123)
  Browser->>Server: Includes session_id in requests
  Server->>Server: $_SESSION["user"] = "Alice"
  Server->>User: Returns page with session data

Key Functions

Function Purpose
session_start() Initializes a session (must run first).
$_SESSION Associative array for session data.
session_destroy() Ends the session and deletes data.
session_unset() Clears session variables (but keeps session ID).

Example: Login Session

<?php
session_start();

// Start session and set user data
$_SESSION["user"] = "Alice";
$_SESSION["logged_in"] = true;

// Retrieve data
if (isset($_SESSION["logged_in"])) {
    echo "Welcome, " . htmlspecialchars($_SESSION["user"]);
}

// Destroy session on logout
session_destroy();
?>

Trace Table:

Step Action Session State ($_SESSION)
1 session_start() Empty array
2 $_SESSION["user"] = "Alice" user → "Alice", logged_in → true
3 session_destroy() All data deleted

3. Cookies vs. Sessions: Key Differences

Feature Cookies Sessions
Storage Client-side (browser) Server-side
Persistence Persists until expiry/cookie delete Ends when server terminates
Security Vulnerable to XSS, tampering More secure (ID-based)
Data Size Limited (~4KB) Unlimited
Use Case Preferences (theme, language) User authentication, carts

Example in Real Life:

  • eSewa/Khalti: Uses sessions to track a user’s payment progress across pages (e.g., selecting amount → confirming → completing).
  • Daraz: Uses cookies to remember items in the shopping cart (persists even after closing the browser).

4. Security in PHP: Threats and Mitigations

PHP applications are vulnerable to attacks like XSS (Cross-Site Scripting), CSRF (Cross-Site Request Forgery), and SQL Injection. Below are defenses.

A. Input Validation

Always validate and sanitize user input to prevent injection attacks.

Example: Validating an Email

<?php
$email = $_POST["email"];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email: " . htmlspecialchars($email);
} else {
    echo "Invalid email!";
}
?>

Trace Table:

Input ($_POST["email"]) filter_var() Check Output
test@example.com true "Valid email: test@example.com"
invalid@.com false "Invalid email!"

B. Output Encoding (Preventing XSS)

Use htmlspecialchars() to escape HTML/JS in output.

Vulnerable Code (XSS Attack):

<?php
echo "<script>alert('Hacked!');</script>"; // Directly outputs malicious script
?>

Secure Code:

<?php
echo htmlspecialchars("<script>alert('Hacked!');</script>");
// Outputs: &lt;script&gt;alert('Hacked!');&lt;/script&gt;
?>

C. SQL Injection Prevention

Use prepared statements with mysqli or PDO.

Insecure Code (SQLi Vulnerable):

<?php
$user = $_POST["user"];
$query = "SELECT * FROM users WHERE username = '$user'";
$result = mysqli_query($conn, $query); // Attacker injects: ' OR '1'='1
?>

Secure Code (Prepared Statement):

<?php
$user = $_POST["user"];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user);
$stmt->execute();
?>

D. Password Hashing

Never store plaintext passwords. Use password_hash() and password_verify().

<?php
// Hashing a password
$password = "secure123";
$hashed = password_hash($password, PASSWORD_BCRYPT);
echo $hashed; // Outputs: $2y$10$N9qo8uLO...

// Verifying a password
$input = "secure123";
if (password_verify($input, $hashed)) {
    echo "Password matches!";
}
?>

5. Real-World Applications

In the Real World

  1. WhatsApp (End-to-End Encryption)

    • Uses sessions to maintain active chat state across devices.
    • Cookies store user preferences (e.g., notification settings).
    • Security: Encrypts session data with TLS to prevent MITM attacks.
  2. NEPSE (Stock Market)

    • Sessions track investor portfolios during trading hours.
    • Cookies remember login tokens for seamless access.
    • Validation: Strict input checks prevent fake trades (e.g., negative shares).
  3. Pathao (Ride-Hailing)

    • Cookies store user location for quick pickup/drop-off.
    • Sessions maintain ride details (e.g., driver assigned, fare).
    • Security: Hashes payment details to prevent fraud.

6. Worked Example: Secure Login System

Scenario: Build a login system with session-based authentication and password hashing.

login.html0login.php1dashboard.php2
File structure of the secure login system example

Step 1: HTML Form (login.html)

<form action="login.php" method="post">
    Username: <input type="text" name="username"><br>
    Password: <input type="password" name="password"><br>
    <input type="submit" value="Login">
</form>

Step 2: PHP Backend (login.php)

<?php
session_start();

// Validate input
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$password = $_POST["password"];

// Check credentials (simulated database)
$valid_users = [
    "admin" => password_hash("admin123", PASSWORD_BCRYPT)
];

if (isset($valid_users[$username]) && password_verify($password, $valid_users[$username])) {
    $_SESSION["user"] = $username;
    $_SESSION["logged_in"] = true;
    header("Location: dashboard.php");
} else {
    die("Invalid credentials!");
}
?>

Step 3: Dashboard (dashboard.php)

<?php
session_start();
if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] !== true) {
    header("Location: login.html");
    exit;
}
echo "Welcome, " . htmlspecialchars($_SESSION["user"]);
?>

Trace Table:

Step Action Session State ($_SESSION) Output
1 User submits admin/admin123 Empty Redirects to login.php
2 password_verify() succeeds user → "admin", logged_in → true Redirects to dashboard.php
3 dashboard.php checks session Same as above "Welcome, admin"
4 User logs out (session_destroy()) All data deleted Redirects to login.html

7. Common Exam Questions and Answers

Q1: How can you generate a unique ID in PHP for sessions?

Answer: Use session_id() to generate or retrieve the session ID, or set a custom one:

session_start();
$_SESSION["custom_id"] = uniqid("USER_", true); // e.g., "USER_5f8d..."

Q2: What is the difference between cookies and sessions?

Answer:

Aspect Cookies Sessions
Storage Browser (client-side) Server (PHP files)
Lifetime Persists until expiry/cookie delete Ends when server terminates session
Security Vulnerable to XSS More secure (ID-based)
Data Size Limited (~4KB) Unlimited
Use Case Preferences, tracking Authentication, carts

Q3: Write a PHP program to create a session and store user data.

Answer:

<?php
session_start();
$_SESSION["name"] = "John Doe";
$_SESSION["role"] = "admin";

// Retrieve data
echo "Name: " . htmlspecialchars($_SESSION["name"]);
echo "<br>Role: " . htmlspecialchars($_SESSION["role"]);

// Destroy session
session_destroy();
?>

Exam Tip

  1. Prioritize Security: Always validate input, use prepared statements, and hash passwords. Examiners love seeing password_hash(), mysqli_real_escape_string(), and htmlspecialchars().
  2. Session Management: Know the lifecycle of sessions (session_start(), $_SESSION, session_destroy()). Draw a flowchart of how a session ID is passed via cookies.
  3. Cookie vs. Session: Compare them in a table with real-world examples (e.g., "Why would Daraz use cookies for carts but sessions for checkout?").
  4. Code Traces: Practice tracing PHP code step-by-step, especially for session/cookie operations. Show the state of $_SESSION or $_COOKIE after each action.
  5. Practical Focus: Expect 1–2 coding questions (e.g., build a login system with sessions). Use session_start() early in your script and always encode output with htmlspecialchars().
  6. Security Threats: Memorize XSS, CSRF, and SQLi. Explain how to prevent them with code snippets (e.g., "Use filter_var() for emails and prepared statements for SQL").

Visual Summary:

mindmap
  root((PHP Security))
    Cookies
      - Client-side storage
      - Set via `setcookie()`
      - Vulnerable to XSS
      - Example: `setcookie("theme", "dark", time()+3600)`
    Sessions
      - Server-side storage
      - Use `session_start()` and `$_SESSION`
      - More secure than cookies
      - Example: `$_SESSION["user"] = "Alice"; session_regenerate_id(true)`
    Security
      - Input validation (`filter_var()`)
      - Output encoding (`htmlspecialchars()`)
      - SQL injection prevention (prepared statements)
      - Password hashing (`password_hash()`)
      - CSRF protection (`csrf_token()`)

Based on the TU BITM syllabus for Web Programming II (IT219), unit 6.

Discussion

Loading…