Sessions

Managing server-side state with PHP sessions and cookies

The Problem: HTTP is Stateless

Each HTTP request is independent. The server has no memory of previous requests:

Request 1: POST /login (username=alice, password=***)
Response: "Login successful!"

Request 2: GET /dashboard
Response: "Who are you? Please log in."  <-- Server forgot!

Without a mechanism to link requests together, the server cannot know that Request 2 comes from the same user who just logged in during Request 1.

The Solution: Sessions

Sessions solve this by storing data on the server and linking it to a browser via a cookie:

Request 1: POST /login
Response: "Login successful!"
          Set-Cookie: PHPSESSID=abc123
          [Server stores: abc123 -> {user: alice}]

Request 2: GET /dashboard
          Cookie: PHPSESSID=abc123
Response: [Server looks up abc123]
          "Welcome, Alice!"

The browser automatically sends the session cookie with every subsequent request. PHP looks up the session ID and restores the associated data into $_SESSION.

Basic Session Usage

session_start() Timing

Understanding when to call session_start() is crucial:

// WRONG - whitespace before PHP

Login Flow

A typical login system involves four components working together:

  1. login-form.php — Show the login form to the user
  2. login-process.php — Validate credentials and create the session
  3. dashboard.php — Check for a valid session and show protected content
  4. logout.php — Destroy the session and clear the cookie

Processing Login

Protecting a Page

Security Best Practices

0, // Session cookie (expires when browser closes) 'path' => '/', 'secure' => true, // HTTPS only 'httponly' => true, // No JavaScript access 'samesite' => 'Lax' // CSRF protection ]); session_start(); // 3. Proper logout - three steps session_start(); $_SESSION = []; // Clear data session_destroy(); // Destroy server storage setcookie(session_name(), '', time() - 3600); // Clear the cookie ?>

Summary

  • HTTP is stateless — sessions add state by storing data on the server and linking it to the browser via a cookie
  • session_start() must be called before any output, just like header()
  • $_SESSION persists data across requests for the same user
  • Proper logout requires clearing the session data, destroying server storage, and removing the cookie
  • Security best practices include regenerating session IDs on login and setting secure cookie parameters