TExcelTAD
Home › PHP › PHP Cookies & Sessions

PHP Cookies & Sessions

HTTP is stateless: each request arrives at the server as if the visitor had never been there before. Yet websites remember your language, your shopping cart and whether you are logged in. They do it with cookies (small values stored by the browser) and sessions (data stored on the server, linked to the browser by a cookie).

Note: Cookies and sessions only make sense when a browser talks to a web server. The playgrounds here run PHP as a command-line script, so the cookie and session code below is shown in normal code blocks with simulated HTTP transcripts. The runnable examples practise the logic using plain arrays.

Cookies

A cookie is a name/value pair that the server asks the browser to keep. You create one with setcookie(), which must be called before any output because it sends an HTTP header:

php
<?php
// theme.php
setcookie('theme', 'dark', [
    'expires'  => time() + 60 * 60 * 24 * 30,  // 30 days
    'path'     => '/',
    'secure'   => true,      // only over HTTPS
    'httponly' => true,      // JavaScript cannot read it
    'samesite' => 'Lax',     // limits cross-site sending
]);
echo 'Theme saved!';

The response carries a Set-Cookie header; on every following request the browser sends the cookie back, and PHP places it in $_COOKIE:

http
HTTP/1.1 200 OK
Set-Cookie: theme=dark; expires=Sun, 13 Apr 2025 09:30:00 GMT; path=/; secure; HttpOnly; SameSite=Lax
Content-Type: text/html; charset=UTF-8

Theme saved!
http
GET /index.php HTTP/1.1
Host: example.test
Cookie: theme=dark
Option Purpose
expires Unix timestamp when the cookie dies; 0 = when the browser closes
path / domain Which URLs receive the cookie
secure Only sent over HTTPS
httponly Hidden from JavaScript (document.cookie) — protects against XSS theft
samesite Strict, Lax or None: controls cross-site requests (CSRF protection)

To delete a cookie, set it again with an expiry time in the past: setcookie('theme', '', ['expires' => 1, 'path' => '/']);.

Reading a cookie is plain array access — and like all input, it can be forged, so validate it:

php · try it yourself
<?php
// Simulate the Cookie header the browser sent
$_COOKIE = ['theme' => 'dark', 'lang' => 'fr<script>'];

$allowedThemes = ['light', 'dark'];
$theme = in_array($_COOKIE['theme'] ?? '', $allowedThemes, true) ? $_COOKIE['theme'] : 'light';

$allowedLangs = ['en', 'vi', 'fr'];
$lang = in_array($_COOKIE['lang'] ?? '', $allowedLangs, true) ? $_COOKIE['lang'] : 'en';

echo "theme = $theme" . PHP_EOL;
echo "lang  = $lang (cookie value was rejected)" . PHP_EOL;
theme = dark
lang  = en (cookie value was rejected)

Tip: Never store secrets or prices in cookies. The user can see and edit every cookie in their browser.

Sessions

A session keeps data on the server. session_start() either resumes the visitor's session or creates a new one with a random ID, which is sent to the browser in a cookie (named PHPSESSID by default). After that, $_SESSION is an ordinary array that PHP saves automatically at the end of the request:

php
<?php
// login.php
session_start();

if (checkPassword($_POST['user'], $_POST['password'])) {
    session_regenerate_id(true);       // new ID after login (prevents session fixation)
    $_SESSION['user'] = $_POST['user'];
    $_SESSION['cart'] = [];
}
php
<?php
// cart.php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: /login.php');
    exit;
}
$_SESSION['cart'][] = 'green-tea';
echo 'Items in cart: ' . count($_SESSION['cart']);

A simulated conversation between the browser and the server:

http
POST /login.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded

user=lan&password=correct-horse

HTTP/1.1 302 Found
Set-Cookie: PHPSESSID=k3v9q1x7m2; path=/; HttpOnly
Location: /cart.php

GET /cart.php HTTP/1.1
Cookie: PHPSESSID=k3v9q1x7m2

HTTP/1.1 200 OK

Items in cart: 1

The browser only ever sees the meaningless ID; the username and cart stay on the server.

Simulating a session store

Under the hood, PHP's default session handler serializes $_SESSION into a file named after the session ID. This playground imitates that idea with an array of "files", so you can see how data survives between requests:

php · try it yourself
<?php
$store = [];   // pretend server-side session storage: id => serialized data

function handleRequest(array &$store, ?string $sessionId, string $item): string
{
    $sessionId ??= 'sess' . (count($store) + 1);          // new visitor: new ID
    $session = isset($store[$sessionId]) ? unserialize($store[$sessionId]) : [];

    $session['cart'][] = $item;                           // work with the data
    $store[$sessionId] = serialize($session);             // saved at end of request

    return $sessionId;
}

$id = handleRequest($store, null, 'tea');   // first request, no cookie yet
handleRequest($store, $id, 'cups');         // browser sends the cookie back
handleRequest($store, $id, 'kettle');

echo "Session ID cookie: $id" . PHP_EOL;
echo "Stored on server:  " . $store[$id] . PHP_EOL;
print_r(unserialize($store[$id])['cart']);
Session ID cookie: sess1
Stored on server:  a:1:{s:4:"cart";a:3:{i:0;s:3:"tea";i:1;s:4:"cups";i:2;s:6:"kettle";}}
Array
(
    [0] => tea
    [1] => cups
    [2] => kettle
)

Ending a session

Logging out should destroy the server data and the cookie:

php
<?php
session_start();
$_SESSION = [];
setcookie(session_name(), '', ['expires' => 1, 'path' => '/']);
session_destroy();

Cookies vs sessions

Cookie Session
Data stored In the browser On the server
Size ~4 KB per cookie Limited only by the server
User can read/modify it Yes No (only the ID)
Lifetime Until expires Until the browser closes or it times out
Good for Preferences, "remember me" tokens Login state, carts, flash messages

Test yourself

Why must setcookie() and session_start() be called before any output?

  1. They are slow
  2. They send HTTP headers, which must come before the body
  3. They clear the output buffer
  4. PHP requires it for security

Where is the data in $_SESSION stored?

  1. In the browser's cookies
  2. In the URL
  3. On the server, found via the session ID cookie
  4. In localStorage

Which cookie option prevents JavaScript from reading the cookie?

  1. secure
  2. samesite
  3. httponly
  4. path