Thuta Learning
PHP
AdvancedProgrammingBeginner

Sessions & Cookies

PHPLesson 2335 min

What you'll walk away with

  • Tell a cookie (stored in the browser) from a session (stored on the server with only an ID in the browser) and pick the right one
  • Explain why session_start() must run before any output and what the headers already sent warning means
  • Prevent session fixation by calling session_regenerate_id(true) after login
  • Describe the HttpOnly, Secure and SameSite flags and write logout and idle timeout correctly

Explain it simply

Sessions and cookies in plain language

A website does not remember a visitor between one page and the next; every request arrives like a stranger. Compare a session to a cloakroom ticket: your coat (the data) stays in the cloakroom, and all you carry is a numbered ticket (the session ID).

A cookie is more like a note you keep in your pocket: the shop hands you some text, your browser stores it and shows it again each time you come back. But the note is in your own hands, so remember that you can edit it.

Problem → Why → Solution

The problem: a cookie you cannot trust and a late session_start

Suppose you remember the logged-in user by putting user_id=5 in a cookie. The cookie lives in the browser, so a visitor can change it to 1 in the developer tools and your system believes they are the admin. A cookie value is 'what the visitor says', not 'what we know'.

The second problem is ordering. If a page echoes a line of HTML and only then calls session_start(), PHP warns 'Session cannot be started after headers have already been sent', because the session cookie travels in a header and headers cannot be sent once the body has started.

login-wrong.php
<?php
echo '<h1>Shop</h1>';                // output has started...
session_start();                     // Warning: headers already sent

setcookie('user_id', '5');           // the visitor can edit this to 1
if (($_COOKIE['user_id'] ?? '') === '1') {
    echo 'Welcome, admin';           // anyone who types 1 gets in
}

Why trusted state belongs on the server

Trusted facts, such as who the user is or whether they are an admin, should not sit in the visitor's hands. A session keeps that data on the server and gives the browser only a random, unguessable ID, so there is nothing for the visitor to edit. The ID itself becomes a secret, though, which is why it needs regeneration and cookie flags to protect it.

Core concept: one ID points at data on the server

HTTP is stateless: every request arrives on its own, and the server does not remember one page view from the next. To remember a visitor (logged in, shopping cart) you need a handle that comes back with every request, and that handle is a cookie. A cookie is a small piece of text the server asks the browser to store and send back with later requests to that site.

Because a cookie lives in the browser, the visitor can read and change it, so never put anything you must trust (prices, is_admin) there. A session keeps the real data on the server (PHP stores one file per visitor by default) and gives the browser only a random session ID in a cookie, named PHPSESSID by default. On each request session_start() reads that cookie, finds the stored data and fills $_SESSION.

text
One request cycle
-----------------
Browser                                   Server
-------                                   ------
GET /cart   (Cookie: PHPSESSID=abc123) -->  session_start()
                                            reads sess_abc123 from disk
                                            fills $_SESSION
                                            page code reads or writes it
            <-- response (+ Set-Cookie if the ID is new)
                                            script ends: $_SESSION saved

session_start() must run before any output, because it sends a Set-Cookie header and headers cannot be sent after the body has started. That is the origin of the 'headers already sent' warning. $_SESSION is an ordinary array you read and write, and its data is saved when the script ends or when you call session_write_close().

A session ID is as valuable as a password while it lives, because whoever holds it is that user. So: (1) when privilege changes, such as at login, call session_regenerate_id(true) for a new ID, which stops session fixation, where an attacker plants an ID they already know before the victim logs in. (2) Set cookie flags: HttpOnly keeps JavaScript, including injected XSS code, from reading the cookie, Secure sends it only over HTTPS, and SameSite stops the browser attaching it to most cross-site requests. (3) Turn on session.use_strict_mode so PHP rejects an ID it never issued. (4) On logout, empty $_SESSION, destroy the session and expire the cookie.

The browser holds an ID, the server holds the data
  1. The browser holds one random ID
  2. The server maps the ID to saved data
  3. session_start() fills $_SESSION
  4. New ID at login, destroy at logout

Anyone who steals the ID steals the session, so protect the ID with cookie flags.

General pattern

php
session_set_cookie_params([...flags]);   // before session_start()
session_start();                         // before any output
$_SESSION['key'] = $value;               // read and write like an array

session_regenerate_id(true);             // when privilege changes
$_SESSION = [];                          // on logout: clear the data,
session_destroy();                       // delete the stored session

Set the cookie parameters before session_start(), start the session before any output, regenerate the ID when privilege changes, and clear then destroy on logout.

Worked example: login, two requests and logout

The command line has no browser, so this sample plays both requests itself. In request one it starts a session, logs in and saves with session_write_close(); in request two it passes session_id() and calls session_start() again, as a browser would do by sending the cookie back. Session files live in a temp directory and are deleted at the end. Notice also that nothing is echoed before the session calls: results are collected in $report and printed at the very end.

session-flow.php
<?php
$report = [];
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'sess_' . bin2hex(random_bytes(4));
mkdir($dir);
$fileFor = fn(string $id): string => $dir . DIRECTORY_SEPARATOR . 'sess_' . $id;

session_save_path($dir);                // keep these demo sessions in a temp folder
session_set_cookie_params([
    'lifetime' => 0,                    // lasts until the browser closes
    'path' => '/',
    'secure' => true,                   // HTTPS only
    'httponly' => true,                 // JavaScript cannot read it
    'samesite' => 'Lax',                // not sent on most cross-site requests
]);

// Request 1: the visitor arrives and then logs in.
session_start();
$guestId = session_id();
$_SESSION['user'] = 'aung';
session_regenerate_id(true);            // new id after login, old one deleted
$memberId = session_id();

$flags = session_get_cookie_params();
$report[] = 'cookie flags: secure=' . var_export($flags['secure'], true)
    . ', httponly=' . var_export($flags['httponly'], true)
    . ', samesite=' . $flags['samesite'];
$report[] = 'id changed after login: ' . var_export($guestId !== $memberId, true);
$oldGone = !file_exists($fileFor($guestId));
$report[] = 'old session file deleted: ' . var_export($oldGone, true);
session_write_close();

// Request 2: the browser sends the same ID back in its cookie.
$_SESSION = [];
session_id($memberId);
session_start();
$report[] = 'request 2 still knows: ' . ($_SESSION['user'] ?? '(nobody)');

// Logout: clear the data, then delete the stored session.
$_SESSION = [];
session_destroy();
$report[] = 'file after logout: ' . var_export(file_exists($fileFor($memberId)), true);
rmdir($dir);

echo implode("\n", $report), "\n";

Code breakdown

  1. Cookie parameters first'httponly' => true,

    session_set_cookie_params() must run before session_start(), because these flags decide how the session cookie is sent. HttpOnly, Secure and SameSite are all switched on here.

  2. Start and store$_SESSION['user'] = 'aung';

    After session_start() the $_SESSION variable is an ordinary array. The value stored under 'user' is saved in the session file on the server and never goes to the browser.

  3. New ID at loginsession_regenerate_id(true);

    As soon as the login succeeds a new ID is issued, and the true argument deletes the file of the old ID. An ID the attacker knew stops working from this moment, while the data moves to the new ID.

  4. Second requestsession_id($memberId);

    On a real server session_start() reads the ID from the cookie by itself. The command line has no cookie, so the ID is supplied by hand to imitate the browser sending it back, and session_start() finds 'aung' again.

  5. Logout properlysession_destroy();

    session_destroy() deletes the session file on the server but does not clear $_SESSION in the running script, which is why $_SESSION = [] comes first. On a real site you would also expire the cookie.

You should see
cookie flags: secure=true, httponly=true, samesite=Lax
id changed after login: true
old session file deleted: true
request 2 still knows: aung
file after logout: false

What each cookie flag tells the browser

The command line cannot show HTTP headers, so you cannot see setcookie() at work there. Running PHP's built-in web server (php -S) and calling it with curl does show the headers actually sent. The first below is the session cookie and the second comes from setcookie('theme', 'dark', [...]). Notice that httponly is left off the theme cookie, because page JavaScript may want to read a preference like that.

text
Set-Cookie: PHPSESSID=<random id>; path=/; secure; HttpOnly; SameSite=Lax
Set-Cookie: theme=dark; path=/; secure; SameSite=Lax
theme-cookie.php
<?php
$sent = setcookie('theme', 'dark', [
    'expires' => 0,          // 0 = until the browser closes
    'path' => '/',
    'secure' => true,
    'httponly' => false,     // a preference page scripts may read
    'samesite' => 'Lax',
]);

echo 'setcookie accepted: ', var_export($sent, true), "\n";
FlagWhat it tells the browser
HttpOnlyhide the cookie from JavaScript (document.cookie), which limits theft through XSS
Securesend it only over HTTPS, never over plain HTTP
SameSite=Laxwithhold it on most cross-site sub-requests, but send it when the visitor follows a link
SameSite=Strictwithhold it on every request that starts from another site
expires / path / domainwhen it expires and which URLs receive it

PHP's built-in defaults leave HttpOnly, Secure and SameSite unset and strict mode off, so you must set them yourself. Instead of session_set_cookie_params() you can use these php.ini settings.

php.ini
session.use_strict_mode = 1
session.use_only_cookies = 1
session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = "Lax"

Session fixation and strict mode

Session fixation means an attacker invents an ID and gets it into the victim's browser (through a link or a forged cookie). If the victim then logs in with that ID, the attacker already knows it. The defence has two parts: issuing a new ID at login (shown in the main example) and turning strict mode on. With strict mode on, PHP refuses an ID that matches no stored session and issues a fresh one instead.

strict-mode.php
<?php
$out = [];
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'sess_' . bin2hex(random_bytes(4));
mkdir($dir);
session_save_path($dir);
$planted = 'plantedbyattacker0123456789abcd';

foreach (['1', '0'] as $strict) {
    ini_set('session.use_strict_mode', $strict);
    session_id($planted);
    session_start();
    $kept = var_export(session_id() === $planted, true);
    $out[] = "strict_mode=$strict keeps the planted id: $kept";
    session_write_close();
    array_map('unlink', glob($dir . DIRECTORY_SEPARATOR . 'sess_*'));
}

echo implode("\n", $out), "\n";
rmdir($dir);
text
strict_mode=1 keeps the planted id: false
strict_mode=0 keeps the planted id: true

Notice that the loop starts with strict mode on and deletes the created file after each round, so that every round starts with an ID that matches no stored session. With strict mode off, PHP happily accepts the planted ID and carries on using it.

Controlling idle timeout yourself

There are two kinds of expiry: the cookie's lifetime (on the browser side) and server-side garbage collection (session.gc_maxlifetime, 1440 seconds by default). GC states the minimum age before a file may be deleted and runs probabilistically, so do not rely on it as an exact timeout. For a precise idle timeout, store last_seen in $_SESSION and compare it on every request.

idle-timeout.php
<?php
function isExpired(array $session, int $now, int $idleSeconds): bool
{
    return !isset($session['last_seen']) || $now - $session['last_seen'] > $idleSeconds;
}

$session = ['user' => 'aung', 'last_seen' => 1_000];   // seconds, not a real clock

foreach ([1_600, 2_000, 2_601] as $now) {
    $expired = isExpired($session, $now, 600);
    echo "now=$now expired=", var_export($expired, true), "\n";
    if (!$expired) {
        $session['last_seen'] = $now;      // activity renews the timer
    }
}
text
now=1600 expired=false
now=2000 expired=false
now=2601 expired=true

In real projects

Sessions and cookies in real projects

Sessions hold login state, shopping carts, flash messages that appear once after a redirect, multi-step forms and CSRF tokens. Preferences such as theme or language often go in cookies, because it does not matter if the visitor edits them and nothing sensitive is exposed.

On a site with more than one server the session file lives on a single machine, so sessions are moved to shared storage such as Redis or a database (session.save_handler). A 'remember me' feature should not stretch the session ID's life; it uses a separate random token in a cookie, with only a hash of it kept in the database. Frameworks such as Laravel and Symfony wrap all of this, but underneath they use the same ideas as this lesson.

Common mistakes

Common mistakes with sessions and cookies

Calling session_start() after output

An echo, some HTML, or even one blank line before <?php counts as output and triggers 'Session cannot be started after headers have already been sent'. Put session_start() at the start of the file, or buffer output with ob_start().

Keeping the same ID after login

Carrying on with an ID the attacker knew before login enables session fixation. Call session_regenerate_id(true) as soon as the password check passes.

Putting trusted data in a cookie

A user_id, role or is_admin in a cookie can be changed by the visitor. Keep those in $_SESSION only.

Logging out with session_destroy() alone

session_destroy() only deletes the server-side data; it leaves $_SESSION in the running script and the cookie in the browser untouched. Set $_SESSION = [] and expire the cookie too.

Treating gc_maxlifetime as an exact timeout

Garbage collection runs probabilistically, so a session can live longer than you expect. For an exact idle timeout, store last_seen in $_SESSION.

Best practices

Best practices

  • Set the session cookie HttpOnly, Secure and SameSite=Lax (or Strict), and turn strict mode on.
  • Call session_regenerate_id(true) at login and whenever privilege increases.
  • Keep trusted facts in the session and only editable preferences in cookies.
  • On logout, clear $_SESSION, call session_destroy() and expire the cookie.

Mini challenge

Mini challenge: login, idle timeout and logout

Write three functions that use $_SESSION: login(string $user, int $now) issues a new ID and stores the user and last_seen, isLoggedIn(int $now, int $idle) returns true only while the idle timeout has not passed and renews last_seen, and logout() clears the session completely. Pass times in as parameters and never read the real clock.

  • login() must call session_regenerate_id(true)
  • isLoggedIn() returns false with no user, false when now - last_seen > idle, otherwise renews last_seen and returns true
  • logout() clears $_SESSION and calls session_destroy()
  • Keep the session in a temp directory and print the results before login, after login, at t=400, 900 and 1600 (idle 600), and after logout
login-flow.php
<?php
function login(string $user, int $now): void
{
    // TODO: issue a new session ID, then store the user and last_seen
}

function isLoggedIn(int $now, int $idle): bool
{
    // TODO: false without a user; false after the idle timeout; otherwise renew last_seen
}

function logout(): void
{
    // TODO: clear $_SESSION, then destroy the stored session
}

$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'flow_' . bin2hex(random_bytes(4));
mkdir($dir);
session_save_path($dir);
session_start();

// TODO: print the state before login, after login(100), at t=400/900/1600, after logout
// TODO: remove the temp directory

Expected: false before login, true after login with a changed ID, true at t=400 and 900, false at t=1600 (700 idle seconds exceeds 600), and the session file is gone after logout.

Show hint

Start isLoggedIn with isset($_SESSION['user'], $_SESSION['last_seen']). To prove the file is removed, remember session_id() before logout and check file_exists() afterwards.

Show solution
login-flow.php
<?php
function login(string $user, int $now): void
{
    session_regenerate_id(true);
    $_SESSION['user'] = $user;
    $_SESSION['last_seen'] = $now;
}

function isLoggedIn(int $now, int $idle): bool
{
    if (!isset($_SESSION['user'], $_SESSION['last_seen'])) {
        return false;
    }
    if ($now - $_SESSION['last_seen'] > $idle) {
        return false;
    }
    $_SESSION['last_seen'] = $now;
    return true;
}

function logout(): void
{
    $_SESSION = [];
    session_destroy();
}

$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'flow_' . bin2hex(random_bytes(4));
mkdir($dir);
session_save_path($dir);
session_start();

$lines = [];
$lines[] = 'before login: ' . var_export(isLoggedIn(0, 600), true);

$before = session_id();
login('aung', 100);
$lines[] = 'after login: ' . var_export(isLoggedIn(100, 600), true);
$lines[] = 'id changed at login: ' . var_export($before !== session_id(), true);

foreach ([400, 900, 1600] as $t) {
    $lines[] = "active at t=$t: " . var_export(isLoggedIn($t, 600), true);
}

$last = session_id();
logout();
$file = $dir . DIRECTORY_SEPARATOR . 'sess_' . $last;
$lines[] = 'session file removed after logout: ' . var_export(!file_exists($file), true);
rmdir($dir);

echo implode("\n", $lines), "\n";

Quick quiz 1 / 3

When you use a PHP session, what does the browser store?

Quick quiz 2 / 3

A visitor has just logged in successfully. What should the code do with the session at that moment?

Quick quiz 3 / 3

Which cookie attribute stops JavaScript on the page, for example injected through XSS, from reading the session cookie?

What to remember

  • A cookie lives in the browser and can be edited by the visitor, while a session keeps data on the server and gives the browser only a random ID.
  • Call session_start() and setcookie() before any output, or you get headers already sent.
  • session_regenerate_id(true) at login, strict mode, and the HttpOnly, Secure and SameSite flags protect the session ID.
  • On logout clear $_SESSION, call session_destroy() and expire the cookie, and check last_seen yourself for an exact idle timeout.

PHP Security Manual — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Sessions & Cookies | Thuta Learning