In this chapter
We'll take a first look at how websites remember visitors over stateless HTTP — cookies set with setcookie() and their security options, sessions that keep data on the server with only an id in a cookie, flash messages, and HTTP Basic authentication for a simple protected page — ready for the full login system in Act 17.
The Problem in Real Life
Olivia has two wishes. Customers like Sam should not have to type their name and favourite barber every time. And the barbers need a schedule page that the public can't see — today, anyone who guesses /schedule.php can read every customer's name and phone number.
Mia stores the favourite barber in a variable and is surprised it's gone on the next page. "HTTP is stateless," Marcus reminds her. "If the server should remember something, the browser has to bring a key back each time."
A cookie is the key the browser carries. A session is the locker on our side that the key opens.
Marcus
Forgetting Every Visitor vs. Cookies and Sessions
Cookies
Small values the browser stores and sends back with every request to the site.
Sessions
Data kept on the server; the browser only holds a random session id.
Who is this?
HTTP Basic authentication asks for a username and password in one header.
Cookies, Sessions and HTTP Authentication: A First Look
Remembering visitors over stateless HTTP: this chapter is a first look; Act 17 builds real logins with password hashing on top of it. It covers:
- Cookies: setcookie(), $_COOKIE and the security options.
- Sessions: session_start(), $_SESSION and the session id.
- Flash messages: data that lasts exactly one request.
- HTTP Basic authentication: a password for a simple page.
Cookies: a cookie is a small named value the server asks the browser to store, with a Set-Cookie response header. The browser then sends it back in a Cookie header with every later request to the same site, and PHP puts it in $_COOKIE. setcookie('preferred_barber', 'ben', [...]) sets one — it's a header, so it must come before any output (chapter 5) — and the cookie appears in $_COOKIE only from the next request on. The real output below shows both. Cookies are stored in the visitor's browser, so the visitor can read and change them: fine for a preference like a favourite barber, never for anything that grants rights, like "isAdmin=1".
<?phpsetcookie('preferred_barber', 'ben', ['expires' => time() + 60 * 60 * 24 * 30, // 30 days'path' => '/','secure' => true,'httponly' => true,'samesite' => 'Lax',]);echo 'this request sees: ', $_COOKIE['preferred_barber'] ?? '(no cookie yet)', "\n";// $ curl -i "http://localhost:8000/misc.php?what=cookie"// Set-Cookie: preferred_barber=ben; expires=Wed, 02 Dec 2026 19:29:01 GMT; Max-Age=2592000; path=/; secure; HttpOnly; SameSite=Lax// this request sees: (no cookie yet)// $ curl -b "preferred_barber=ben" "http://localhost:8000/misc.php?what=cookie"// this request sees: ben
Cookie options: the options array decides how safe a cookie is. expires sets when it disappears (without it, it's deleted when the browser closes); path limits which URLs receive it. secure => true sends it only over HTTPS; httponly => true hides it from JavaScript, so an XSS bug (chapter 8) can't steal it; samesite => 'Lax' stops the browser sending it with most requests started by other sites — a strong defence against CSRF (chapter 7). For anything important, use all three. To delete a cookie, set it again with an expires time in the past.
Sessions: a session keeps data on the server. session_start() — again before any output — looks for a session id cookie, PHPSESSID by default. If there's none, PHP creates a long random id, sends it as a cookie, and starts an empty $_SESSION array. Whatever you put in $_SESSION is saved on the server at the end of the request (in files by default; Redis or a database later, Act 25) and loaded again on the next request with the same id. The visitor only ever holds the id and can't see or change the data. The diagram below shows the round trip, and the output shows a counter surviving two requests. PHP also sends no-cache headers with sessions, so private pages aren't stored by shared caches.
| Cookie | Session | |
|---|---|---|
| Data stored | In the browser | On the server |
| Visitor can read and change it? | Yes | No — only the id |
| Size | About 4 KB per cookie | As much as the server allows |
| Lasts | Until expires (or browser closes) | Until the session times out or is destroyed |
| Good for | Preferences: favourite barber, language | Login state, flash messages, a basket |
A session round trip
Request 1: no cookie
session_start() creates id p9fjl… and empty $_SESSION
Response 1: Set-Cookie: PHPSESSID=p9fjl…
$_SESSION['views'] = 1 saved on the server
Request 2: Cookie: PHPSESSID=p9fjl…
session_start() loads views = 1 from the server
The browser only holds the id
the data never leaves the server
<?phpsession_start();$_SESSION['views'] = ($_SESSION['views'] ?? 0) + 1;echo "session id: ", session_id(), "\nviews: {$_SESSION['views']}\n";// $ curl -i -c jar.txt "http://localhost:8000/misc.php?what=session"// Set-Cookie: PHPSESSID=p9fjldpuuj8dpciraqjp46qgmb; path=/// Cache-Control: no-store, no-cache, must-revalidate// session id: p9fjldpuuj8dpciraqjp46qgmb// views: 1// $ curl -b jar.txt "http://localhost:8000/misc.php?what=session" # sends the cookie back// session id: p9fjldpuuj8dpciraqjp46qgmb// views: 2
Session security, in brief: whoever has the session id is that visitor, so protect it: HTTPS only, the cookie HttpOnly and SameSite (set with session_set_cookie_params() or php.ini's session.cookie_* settings), and session.use_strict_mode on. After a login, call session_regenerate_id(true) so an id known before login is worthless afterwards (session fixation). Act 17 builds all of this into a real login.
Flash messages: a common use of sessions is a message that survives exactly one redirect: after Post/Redirect/Get, the POST stores $_SESSION['flash'] = 'Booking #4811 confirmed', and the GET page shows it once and removes it. Without the session, the message would be lost in the redirect.
<?phpsession_start();// in book.php, on POST, after saving:$_SESSION['flash'] = "Booking #4811 confirmed — see you Friday at 16:00";header('Location: /booked.php?id=4811', true, 303);exit;// in booked.php, on GET:// $flash = $_SESSION['flash'] ?? null;// unset($_SESSION['flash']); // shown once, then gone// if ($flash !== null) { echo '<p class="flash">', e($flash), '</p>'; }
HTTP Basic authentication: the simplest login is built into HTTP itself. The server answers 401 Unauthorized with WWW-Authenticate: Basic realm="BookBay admin"; the browser shows a username-and-password box and sends the answers in an Authorization header with every request; PHP puts them in $_SERVER['PHP_AUTH_USER'] and PHP_AUTH_PW. Basic auth sends the password only encoded (Base64), not encrypted — so HTTPS is mandatory — has no logout button, and no "forgot password". It's fine for an internal tool or a staging site; customers and barbers get a real login in Act 17. Compare passwords with hash_equals(), which takes the same time whatever the input, so attackers can't guess characters by timing.
<?php$user = $_SERVER['PHP_AUTH_USER'] ?? null;$pass = $_SERVER['PHP_AUTH_PW'] ?? null;if ($user !== 'olivia' || !hash_equals('launch-day', (string) $pass)) { // a demo password!header('WWW-Authenticate: Basic realm="BookBay admin"');http_response_code(401);echo "Login required\n";exit;}echo "Hello, {$user}\n";// $ curl -i "http://localhost:8000/misc.php?what=basic"// HTTP/1.1 401 Unauthorized// WWW-Authenticate: Basic realm="BookBay admin"// Login required// $ curl -u olivia:launch-day "http://localhost:8000/misc.php?what=basic"// Hello, olivia
Key Takeaway
HTTP is stateless, so sites remember visitors with cookies: setcookie() sends Set-Cookie (before output), the browser returns it with every request, and $_COOKIE has it from the next request on — visitor-editable, so only for harmless preferences. Use secure, httponly and samesite=Lax for anything important. Sessions keep data on the server in $_SESSION, keyed by a random PHPSESSID cookie: session_start() before output, regenerate the id after login, HTTPS and HttpOnly/SameSite cookies. Flash messages use the session to survive one redirect. HTTP Basic auth (401 + WWW-Authenticate, PHP_AUTH_USER/PW, hash_equals) suits internal tools over HTTPS; real logins come in Act 17.
Why This Matters
Every logged-in page on the web runs on cookies and sessions. Understanding the id-in-a-cookie, data-on-the-server split is what makes Act 17's login system — and Laravel's — make sense.
Cookie options are also some of the cheapest security settings there are: HttpOnly, Secure and SameSite block whole classes of attacks with three words.
Sam's favourite barber is remembered in a cookie, flash messages survive redirects, and the staging admin page asks for a password. Then the partner who builds Tom's own website writes: their JavaScript can't read BookBay's free slots — "blocked by CORS policy". And Marcus asks a worrying question: if Sam is logged in and visits another site, can that site make his browser submit BookBay's booking form? That's the next chapter: CORS and CSRF.
