Starting Sessions

Starting a Session and Using $_SESSION

session_start() reads the ID from the PHPSESSID cookie and loads its data into $_SESSION; for a new visitor it creates a random 32-character ID and sends the cookie. When the script ends, PHP serializes $_SESSION back to storage. Nothing in it ever reaches the browser.

cart.php: a bookshop cart kept in the sessionPHP
<?php
declare(strict_types=1);
session_start();
$_SESSION['cart'] ??= [];
if (isset($_GET['add']) && preg_match('/^BK-\d{3}$/', $_GET['add'])) {
  $_SESSION['cart'][$_GET['add']] = ($_SESSION['cart'][$_GET['add']] ?? 0) + 1;
}
header('Content-Type: text/plain');
foreach ($_SESSION['cart'] as $sku => $qty) echo "$sku x $qty\n";
Output
$ curl -si -c cart.txt '127.0.0.1:8215/cart.php?add=BK-101' | fold_cookies
...
Set-Cookie: PHPSESSID=e49f84553c8959ebb2f7afde304f7167;
    path=/; secure; HttpOnly; SameSite=Lax
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
...
BK-101 x 1
$ curl -s -b cart.txt '127.0.0.1:8215/cart.php?add=BK-207'
BK-101 x 1
BK-207 x 1
$ sudo cat /var/lib/php/sessions/sess_$(awk '$6 == "PHPSESSID" {print $7}' cart.txt); echo
cart|a:2:{s:6:"BK-101";i:1;s:6:"BK-207";i:1;}

The file uses the default php serialize format: each top-level key, a |, then the serialize() form of its value (Serialization). It is owned by www-data with mode 600, in a directory with mode 1733, where PHP can create files but nobody can list them. The 1981 Expires and no-store come from session.cache_limiter = nocache, so no proxy serves one visitor's cart to another.