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
// 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.
<?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):
- User posts email and password.
- Server finds the user and checks the password (Unit 11 and 13).
- If correct:
session_regenerate_id(true); $_SESSION['user_id'] = $id; - Every protected page begins with:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}| Cookie | Session |
|---|---|
| Stored in the browser | Stored on the server (ID in a cookie) |
| User can change it | User cannot see or change data |
| Can last months | Normally ends when the browser closes or after about 24 minutes idle |
| Small data | Larger, 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.