CodeBlanks Logo Icon CodeBlanks

Session fixation prevention

PHP course · Expert · Lesson 32/54

Learn to prevent session fixation attacks with session_regenerate_id().

What is session fixation?

In a session fixation attack the attacker fixes the victim's session ID to a known value. When the victim logs in, the attacker reuses the same ID to access the account. Defense: on successful login call session_regenerate_id(true); it deletes the old ID and issues a fresh random one.

The true argument also deletes the old session file; leaving false keeps the old ID valid. Cookie parameters must also be hardened: httponly blocks JavaScript, samesite reduces CSRF, secure restricts to HTTPS. Application cookies use setcookie with the same flags.

Hardening cookie parameters

session_set_cookie_params() takes an array: lifetime, path, domain, secure, httponly and samesite. samesite should be 'Strict' or 'Lax'; Strict blocks cross-site carriage entirely, Lax allows top-level navigation.

secure true sends the cookie only over HTTPS. httponly true closes document.cookie access. When session_regenerate_id(true) is called after these settings, the new ID arrives in a hardened cookie. Read the current values with session_get_cookie_params().

Exercise Rotate the session ID

Start the session with @session_start(). Read the old ID with $before = session_id(). Rotate and delete the old data with @session_regenerate_id(true). Read the new ID with $after = session_id(). Check whether the old and new IDs differ and whether the new ID is non-empty; print each result as 1/0.

Show example solution
Write @session_start(); $before = session_id(); @session_regenerate_id(true); $after = session_id();. $before !== $after is always true (1) and strlen($after) > 0 is always true (1). Print two lines with echo.
Example solution:
<?php
@session_start();
$before = session_id();
@session_regenerate_id(true);
$after = session_id();
echo ($before !== $after ? "1" : "0") . "\n";
echo (strlen($after) > 0 ? "1" : "0") . "\n";

Test yourself

  1. Match the session security concepts

    session_regenerate_id
    Rotates the ID
    httponly
    Blocks JavaScript
    samesite
    Reduces CSRF
    secure
    HTTPS only
  2. What does the true argument of session_regenerate_id(true) do?

    • Lengthens the new ID
    • Closes the session at once
    • Deletes the old session data
    • Enforces HTTPS
    Show answer

    Deletes the old session data — Correct. The true argument deletes the old session file; fixation is fully closed.

  3. Complete the session_regenerate_id call

    ____(true);
    Show answer
    session_regenerate_id(true);

All lessons in Expert