Unit 10 · Back-End Programming

10.3Session Management: Cookies and Sessions

HTTP is stateless: the server forgets you after each request. To remember a visitor (logged in? cart contents?) we use cookies and sessions.

Cookies

A cookie is a small piece of data the server asks the browser to store and send back with every later request to that site.

PHP
<?php
// Set (before any output): name, value, options
setcookie('theme', 'dark', [
    'expires'  => time() + 60 * 60 * 24 * 30,   // 30 days
    'path'     => '/',
    'secure'   => false,                         // true on HTTPS sites
    'httponly' => true,                          // JavaScript cannot read it
    'samesite' => 'Lax'
]);

// Read (available on the NEXT request)
$theme = $_COOKIE['theme'] ?? 'light';

// Delete: set expiry in the past
setcookie('theme', '', time() - 3600, '/');

Cookies live in the browser, so the user can read and edit them. Never store passwords or trusted data in plain cookies. Typical uses: language, theme, tracking consent, a remember-me token (see Unit 13). Limits: about 4 KB each. Law (e.g. GDPR) requires consent for non-essential cookies.

Sessions

A session keeps data on the server. The browser only holds a random session ID in a cookie (PHPSESSID). The ID is the key to the data.

shop.lkBrowser cookie storagePHPSESSID = a1b2c3…theme = darkuser can see and edit theseWeb serverSession store (on the server)a1b2c3 → user_id: 15 cart: [5 => 2, 9 => 1]user cannot see or change itrequest + Cookie: PHPSESSID=a1b2c3look up the ID
A session keeps the data on the server; the browser only holds the random session ID in a cookie
PHP
<?php
session_start();                     // MUST be the first thing, before any output

$_SESSION['user_id'] = 15;           // store
$_SESSION['username'] = 'nimal';
$_SESSION['cart'] = [];

echo $_SESSION['username'] ?? 'Guest';   // read

unset($_SESSION['cart']);            // remove one item

// Logout: destroy everything
$_SESSION = [];
session_destroy();
setcookie(session_name(), '', time() - 3600, '/');

Login flow (pseudo-code):

  1. User posts email and password.
  2. Server finds the user and checks the password (Unit 11 and 13).
  3. If correct: session_regenerate_id(true); $_SESSION['user_id'] = $id;
  4. Every protected page begins with:
PHP
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
CookieSession
Stored in the browserStored on the server (ID in a cookie)
User can change itUser cannot see or change data
Can last monthsNormally ends when the browser closes or after about 24 minutes idle
Small dataLarger, safer data

Security rules: call session_regenerate_id(true) right after login (prevents session fixation); set httponly and secure cookie flags in production; destroy the session fully on logout; use HTTPS.

Try it: Build a page counter that stores visits in a session. Build a simple login (hard-coded user), protected dashboard.php, and logout.php. Add a "Remember my theme" cookie.

Check yourself. The questions for this part are on the 10.4 Review Questions page, with answers to check your work.