PHP Advent

#[Production]

PHP Session Security: Cookies, Fixation, and Production

By Charles Hickle ·

An ultrawide curved monitor in a dark security operations center displays encrypted session data streams, authentication directives, and status indicators beside an illuminated keyboard with a plugged-in hardware security key and an open notebook of state transition diagrams.

For production PHP sessions, set the Secure, HttpOnly, and SameSite cookie attributes, enable strict mode, and regenerate the session identifier whenever privileges change. Keep session storage private and make logout expire the browser cookie as well as clear the server data. PHP's default session configuration leaves applications exposed to session fixation, cookie theft through cross-site scripting, and unauthorized access across network boundaries.

PHP keeps state between HTTP requests by giving the browser a session identifier cookie and storing the associated data on the server. That token represents the visitor's authenticated identity. Anyone who obtains or predicts it inherits the user's privileges. Laravel and Symfony wrap session handling in higher-level APIs, but they still depend on PHP's runtime settings or implement the same lifecycle themselves. Knowing what the session module does helps you check those settings and catch regressions that could expose user accounts.

Why Default PHP Session Settings Fall Short

PHP's session defaults favor backward compatibility. A standard installation with an unchanged php.ini accepts behavior that leaves applications open to familiar attacks.

The official PHP session security INI documentation describes the defaults you need to change:

  • Adaptive Session Management: By default, session.use_strict_mode is disabled (0). In this mode, PHP accepts any session identifier supplied by the client, even if the server has never seen or initialized that identifier before. If a visitor sends PHPSESSID=attacker-chosen-value, PHP creates a new session using that exact identifier. This allows session fixation attacks where an attacker pre-seeds a victim with a known token.
  • Unencrypted Cookie Transport: By default, session.cookie_secure is disabled (0). The browser transmits the session cookie over unencrypted HTTP connections, leaving the token vulnerable to network sniffing, local Wi-Fi interception, and proxy caching.
  • JavaScript Cookie Access: By default, session.cookie_httponly is disabled (0). Any cross-site scripting vulnerability on your domain allows client-side scripts to read document.cookie and exfiltrate the active session token to an external server.
  • Missing SameSite Attribute: By default, session.cookie_samesite is empty. Set an explicit policy and keep CSRF tokens for state-changing actions; SameSite alone is not a complete CSRF defense.
  • Shared Storage Location: The default session.save_path is empty, and the file handler commonly uses the system temporary directory. Check the effective path and permissions as described in the storage section below.

As the PHP session management basics guide explains, the session engine cannot tell whether someone presenting an identifier is the user who created it. You have to protect that identifier from disclosure and tampering for as long as the session exists.

The Production php.ini Session Baseline

Set the session directives in php.ini or your pool definition so that scripts get the same defensive defaults before application bootstrap code runs.

Use this production baseline in php.ini:

; Prevent PHP from accepting uninitialized session IDs from clients
session.use_strict_mode = 1

; Ensure session IDs are only passed via cookies, never URL query strings
session.use_cookies = 1
session.use_only_cookies = 1

; Disable transparent session ID passing in URLs (deprecated in PHP 8.4)
session.use_trans_sid = 0

; Restrict session cookies to HTTPS connections only
session.cookie_secure = 1

; Prevent client-side scripts from accessing the session cookie via JavaScript
session.cookie_httponly = 1

; Mitigate cross-site request forgery by controlling cross-site cookie transmission
session.cookie_samesite = "Lax"

; Expire the session cookie when the browser closes
session.cookie_lifetime = 0

; Instruct intermediate caches and proxies not to cache authenticated responses
session.cache_limiter = nocache

; Store session files in a private, unshared directory with 0700 permissions
session.save_handler = files
session.save_path = "/var/lib/php/sessions"

The settings control which identifiers PHP accepts, how browsers send cookies, and where PHP stores session data.

Strict Mode: session.use_strict_mode = 1

With session.use_strict_mode enabled, PHP checks incoming session identifiers against the configured storage backend. If a request supplies an identifier that has not been initialized, PHP discards it and generates a fresh, cryptographically random one. This stops the classic fixation attempt in which an attacker chooses an arbitrary identifier and forces it onto a victim.

Cookie Transport Controls: session.use_only_cookies and session.use_trans_sid

Together, session.use_cookies = 1 and session.use_only_cookies = 1 restrict session tokens to cookies in HTTP request headers. PHP will not look for session keys in $_GET or $_POST. Apply these settings in every environment.

Setting session.use_trans_sid = 0 disables transparent session identifier URL rewriting. With this feature enabled, PHP can append ?PHPSESSID=... to links when cookies are unavailable. Tokens can then leak through browser history, shared bookmarks, referrer headers, and server logs. Enabling this feature is deprecated as of PHP 8.4. Keep it off.

Cookie Security Flags: Secure, HttpOnly, and SameSite

The settings session.cookie_secure, session.cookie_httponly, and session.cookie_samesite control how the browser handles the Set-Cookie header:

  • session.cookie_secure = 1 instructs the browser to attach the cookie only when issuing requests over encrypted TLS connections. If a user accidentally visits an http:// link on your domain before receiving an HTTP 301 redirect to HTTPS, the browser will not send the session token over cleartext wire.
  • session.cookie_httponly = 1 sets the HttpOnly flag on the response header. Web browsers block client scripts from reading or writing this cookie through document.cookie. While HttpOnly does not stop an attacker from making authenticated API calls directly from a compromised page, it prevents the silent exfiltration of the credential for offline use.
  • session.cookie_samesite = "Lax" keeps the cookie off most cross-site subrequests and POST forms while allowing it on top-level GET navigation. Use CSRF tokens for actions that change state, and do not make state changes on GET. Strict also withholds the cookie on cross-site top-level navigation, which may disrupt sign-in links and other flows.
A curved workstation monitor displays cookie security attributes converging into an encrypted session token pipeline with luminous green verification rings.

Identifier Generation

Let PHP generate session identifiers. The runtime configuration manual says changing session.sid_length and session.sid_bits_per_character from their defaults is deprecated as of PHP 8.4; do not copy older hardening recipes that set them. Protect generated identifiers in transit and storage instead.

Programmatic Session Configuration with session_start

Application code may need to set or verify session options even when the server has suitable php.ini defaults. PHP 7.3 and newer let you pass an options array directly to session_start(). You can set the security flags there without changing global server settings or using deprecated runtime calls.

Initialize the session with these options:

<?php

declare(strict_types=1);

function start_secure_session(): void
{
    if (session_status() === PHP_SESSION_ACTIVE) {
        return;
    }

    session_start([
        'use_strict_mode' => 1,
        'use_only_cookies' => 1,
        'cookie_lifetime' => 0,
        'cookie_path' => '/',
        'cookie_domain' => '',
        'cookie_secure' => true,
        'cookie_httponly' => true,
        'cookie_samesite' => 'Lax',
        'cache_limiter' => 'nocache',
    ]);
}

Keeping these options in session_start() has two benefits:

  1. The configuration lives in the application bootstrap, so individual workers and multi-tenant codebases do not depend on the host machine's php.ini.
  2. It sets SameSite in the session cookie directly. Before PHP 7.3, functions such as session_set_cookie_params() needed complicated header manipulation to do this.

Preventing Session Fixation with Strict Mode and Regeneration

In a session fixation attack, the attacker gets a victim to use a known session identifier. The attacker waits for the victim to log in, then uses the same identifier to access the victim's account.

Without protection, the attack works like this:

  1. The attacker visits your web application and receives a valid session token (e.g., PHPSESSID=session-xyz-123).
  2. The attacker crafts a link or injects a cookie on a shared domain containing session-xyz-123 and sends it to the victim.
  3. The victim opens the link and logs into their account using their personal credentials.
  4. If the application keeps the same session token across the login transition, the session associated with session-xyz-123 is now elevated to an authenticated user account.
  5. The attacker, who already possesses session-xyz-123, accesses the application and inherits full control of the victim profile.

Strict mode and identifier regeneration address different parts of this attack.

Strict Mode Defense

Strict mode rejects an arbitrary, uninitialized token, but an attacker can obtain a valid guest session from your server. If the victim uses that initialized guest token, strict mode accepts it. This is why strict mode alone does not stop fixation.

Identifier Regeneration on Privilege Elevation

When authentication succeeds, invalidate the pre-authentication identifier and issue a fresh one.

The OWASP Session Management Cheat Sheet requires session ID regeneration after any privilege change. Login is the most common case: an anonymous guest becomes an authenticated user. Regenerate the identifier for these changes too:

  • Changing account passwords or security settings
  • Elevating permissions from a regular user to an administrator
  • Switching user tenants in a multi-tenant application
  • Completing a multi-factor authentication (MFA) step

Call session_regenerate_id() before writing authenticated state. The session_regenerate_id documentation warns that deleting old data immediately can cause lost sessions and races on unstable networks or concurrent requests.

Two hardware security keys on a wooden desk contrast an inactive matte token with a newly regenerated key illuminated by a glowing cyan indicator.

This authentication handler regenerates the identifier before storing the authenticated user state:

<?php

declare(strict_types=1);

function authenticate_user(string $email, string $password, PDO $db): bool
{
    start_secure_session();

    $stmt = $db->prepare('SELECT id, password_hash, role FROM users WHERE email = :email');
    $stmt->execute(['email' => $email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($password, $user['password_hash'])) {
        return false;
    }

    // Rotate before recording authenticated state
    if (!session_regenerate_id(false)) {
        throw new RuntimeException('Failed to regenerate session identifier.');
    }

    // Populate authenticated user state
    $_SESSION['authenticated_user_id'] = (int)$user['id'];
    $_SESSION['authenticated_role'] = (string)$user['role'];
    $_SESSION['auth_timestamp'] = time();
    $_SESSION['last_activity'] = time();

    // Rotate CSRF token on privilege escalation
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

    return true;
}

Concurrency and Race Conditions During Regeneration

With false, the old guest record still exists. It must never become authenticated: this example rotates the ID before storing the user ID. For stricter invalidation, record an obsolete timestamp in the old session and reject it in request middleware. Plan how parallel requests receive the new cookie and how obsolete records are cleaned up. Regeneration alone does not solve concurrent request handling.

Before and After: Authentication and Session Transition

To illustrate the vulnerability and its remediation, examine an authentication script before and after applying session hardening.

Before: Vulnerable Authentication Script

Here is an authentication routine common in unhardened PHP codebases:

<?php

// Before: Insecure login handling
session_start();

$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

$stmt = $db->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

if ($user && password_verify($password, $user['password_hash'])) {
    $_SESSION['user_id'] = $user['id'];
    header('Location: /dashboard');
    exit;
}

This implementation suffers from several distinct vulnerabilities:

  1. It calls session_start() without enforcing session.use_strict_mode or verifying cookie attributes.
  2. It leaves the existing session identifier intact across the guest-to-authenticated transition. An attacker who planted a known cookie on the victim browser inherits full access to the dashboard.
  3. It does not generate or rotate an anti-CSRF token upon login.
  4. It fails to record login timestamps or establish an idle session timeout window.

After: Hardened Authentication Script

The corrected version retains the exact same business logic (looking up the user, checking the hash, setting the ID, and redirecting) while eliminating the security flaws:

<?php

// After: Hardened login handling
start_secure_session();

$email = (string)($_POST['email'] ?? '');
$password = (string)($_POST['password'] ?? '');

$stmt = $db->prepare('SELECT id, password_hash FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify($password, (string)$user['password_hash'])) {
    if (!session_regenerate_id(false)) {
        throw new RuntimeException('Failed to regenerate session identifier.');
    }
    $_SESSION['user_id'] = (int)$user['id'];
    $_SESSION['auth_time'] = time();
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

    header('Location: /dashboard');
    exit;
}

The refactored code rotates the identifier before adding the user ID and records a timestamp and fresh CSRF secret.

Dual workstation monitors contrast a broken session flow marked by warning icons with a hardened cryptographic authentication pipeline in green.

Ending a Session Completely: The Real Logout Sequence

The PHP session_destroy reference manual describes two limits:

  1. session_destroy() deletes the session record from the server storage backend, such as a file in /var/lib/php/sessions or a Redis key, but it **does not unset the $_SESSION superglobal** in the current process memory. Any code executing later in the same request can still read values from $_SESSION.
  2. session_destroy() does not delete the session cookie on the client browser. The browser retains the cookie and continues sending the old identifier on subsequent requests until the cookie expires naturally.

If strict mode is off, the browser's old cookie may also initialize another active session.

Logout needs four steps:

  1. Initialize the session if it is not already running.
  2. Clear the $_SESSION superglobal array in memory. It is an ordinary PHP array populated during session_start(); assigning $_SESSION = []; clears it for the rest of the request.
  3. Overwrite and expire the session cookie on the client using matching domain, path, and security flags.
  4. Delete the server-side session data using session_destroy().

The logout function performs each step explicitly:

<?php

declare(strict_types=1);

function terminate_session(): void
{
    // Step 1: Ensure the session is active so we have access to metadata
    if (session_status() === PHP_SESSION_NONE) {
        start_secure_session();
    }

    // Step 2: Clear all session variables in current memory
    $_SESSION = [];

    // Step 3: Expire the session cookie in the user browser
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        
        setcookie(
            session_name(),
            '',
            [
                'expires' => time() - 42000,
                'path' => $params['path'],
                'domain' => $params['domain'],
                'secure' => (bool)$params['secure'],
                'httponly' => (bool)$params['httponly'],
                'samesite' => $params['samesite'] ?: 'Lax',
            ]
        );
    }

    // Step 4: Destroy the server-side storage payload
    session_destroy();
}

The past expiration timestamp (time() - 42000) tells the browser to delete the cookie immediately. The call uses the same path, domain, secure, and samesite settings as the original cookie. If the path or domain differs, the browser ignores the deletion instruction and keeps the active cookie.

An open engineering notebook under warm desk lighting details a four-stage session teardown sequence with verification checkmarks beside a brass drafting pencil.

Production Session Storage Choices

Session storage affects both reliability and security. PHP uses local files by default; larger deployments may need a shared backend.

Default Filesystem Storage

PHP serializes session contents and writes them under session.save_path. File storage needs no additional dependencies, but permissions, locks, and multiple web servers need attention:

  • File Permissions: Check the effective session.save_path. PHP's file handler creates files with mode 0600 by default, but a shared temporary directory can expose file names and create multi-tenant risks. Configure a private directory owned by the PHP process user with 0700 permissions.
  • Exclusive File Locking: When session_start() executes, PHP opens the session file and acquires an exclusive flock lock. The lock remains active until the script completes execution or explicitly calls session_write_close(). If a single user opens five tabs or fires multiple concurrent AJAX requests, PHP processes those requests sequentially, not in parallel. Each subsequent request waits for the previous request to finish and release the session lock.
  • Shared Filesystem Inconsistency: Storing sessions on a local disk fails in horizontally scaled environments. If request 1 hits web server A and request 2 hits web server B, server B will not have the session file stored on server A, forcing the user to log in again.

Release the session lock as soon as you finish changing session data. Otherwise, a slow endpoint that streams a download or waits for an external API can block the user's other requests:

<?php

start_secure_session();

// Read or update necessary session values
$userId = $_SESSION['user_id'] ?? null;
$_SESSION['last_view'] = time();

// Release the exclusive file lock immediately
session_write_close();

// Long-running application logic proceeds without blocking other requests
process_large_report($userId);

Redis and Memcached Storage

When several web nodes serve traffic behind a load balancer, a centralized memory cache gives them fast, shared session storage.

David Coallier's PHP Advent article on scalable session storage strategies examines how Memcached and Redis let clusters share session state without sticky load balancing sessions.

Choose between Redis and Memcached with session loss in mind:

  • Memcached: Extremely fast in-memory key-value caching. However, standard Memcached is strictly ephemeral. If a Memcached node restarts or runs out of allocated memory, it evicts or loses session keys, causing instant user logouts.
  • Redis: Supports key expiration and optional persistence or replication. Whether sessions survive a restart depends on your Redis configuration; verify the behavior you want during failover and recovery.

To configure Redis as your session handler in php.ini using the phpredis extension:

session.save_handler = redis
session.save_path = "tcp://10.0.1.50:6379?auth=your_strong_password&prefix=sess_"

Measure the latency of network calls when choosing a backend. As our guide to PHP profiling explains, high wall time with low CPU time often points to external I/O waits. A session handler that opens an unpooled TCP connection to Redis on every HTTP request adds that wait to every response.

Custom Storage with SessionHandlerInterface

PHP 5.4 introduced SessionHandlerInterface for custom session storage. You can back a handler with a relational database such as PostgreSQL or MySQL, a document store, or an encrypted key vault.

Custom handlers also need SessionUpdateTimestampHandlerInterface, available since PHP 7.0, to support session.use_strict_mode = 1. The default file and Redis handlers check storage automatically. A custom handler uses validateId($sessionId) to check whether a supplied identifier exists in your datastore. If the method returns false, PHP generates a new identifier. Without validateId(), PHP cannot make that check for an identifier supplied by an attacker.

This database session handler includes the validation method:

<?php

declare(strict_types=1);

class SecureDatabaseSessionHandler implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface
{
    public function __construct(private PDO $pdo) {}

    public function open(string $path, string $name): bool
    {
        return true;
    }

    public function close(): bool
    {
        return true;
    }

    public function read(string $id): string|false
    {
        $stmt = $this->pdo->prepare('SELECT payload FROM app_sessions WHERE id = :id AND expires_at > :now');
        $stmt->execute(['id' => $id, 'now' => time()]);
        $result = $stmt->fetchColumn();

        return is_string($result) ? $result : '';
    }

    public function write(string $id, string $data): bool
    {
        $lifetime = (int)ini_get('session.gc_maxlifetime');
        $expiresAt = time() + ($lifetime > 0 ? $lifetime : 1440);

        $stmt = $this->pdo->prepare('
            INSERT INTO app_sessions (id, payload, expires_at)
            VALUES (:id, :payload, :expires_at)
            ON CONFLICT (id) DO UPDATE SET
                payload = EXCLUDED.payload,
                expires_at = EXCLUDED.expires_at
        ');

        return $stmt->execute([
            'id' => $id,
            'payload' => $data,
            'expires_at' => $expiresAt,
        ]);
    }

    public function destroy(string $id): bool
    {
        $stmt = $this->pdo->prepare('DELETE FROM app_sessions WHERE id = :id');
        return $stmt->execute(['id' => $id]);
    }

    public function gc(int $max_lifetime): int|false
    {
        $stmt = $this->pdo->prepare('DELETE FROM app_sessions WHERE expires_at < :now');
        $stmt->execute(['now' => time()]);
        return $stmt->rowCount();
    }

    public function validateId(string $id): bool
    {
        $stmt = $this->pdo->prepare('SELECT 1 FROM app_sessions WHERE id = :id AND expires_at > :now');
        $stmt->execute(['id' => $id, 'now' => time()]);
        return (bool)$stmt->fetchColumn();
    }

    public function updateTimestamp(string $id, string $data): bool
    {
        $lifetime = (int)ini_get('session.gc_maxlifetime');

        $stmt = $this->pdo->prepare('UPDATE app_sessions SET expires_at = :expires_at WHERE id = :id');
        return $stmt->execute(['id' => $id, 'expires_at' => time() + ($lifetime > 0 ? $lifetime : 1440)]);
    }
}

Register the handler with session_set_save_handler() before calling session_start(). PHP then stores session data in your database with strict mode support.

Worker Mode and Persistent Runtimes

FrankenPHP and RoadRunner can keep the application framework in memory between requests. Our comparison of PHP worker mode architectures explains how persistent processes avoid repeated framework bootstrapping.

With worker mode, check how session state survives or gets cleared between requests:

  • Persistent Superglobals: In standard PHP-FPM, PHP resets $_SESSION, $_GET, $_POST, and $_COOKIE at request shutdown (RSHUTDOWN). In a persistent worker runtime, if your code fails to close or clean up session state, values from request A can leak into the execution context of request B.
  • Unclosed Session Locks: If a worker handling request A opens a session and encounters an unhandled exception before closing it, the session file lock can remain held or the memory handler can remain attached.
  • Session ID Invalidation: Runtimes like FrankenPHP emulate request superglobals inside their request loop. Always verify that your application framework (such as Symfony HttpFoundation or Laravel SessionManager) explicitly resets its session driver instance at the start of every worker request cycle.

For a persistent worker, verify the framework's documented request reset behavior and close an active session before the response ends. Test consecutive requests from different users for state leakage.

Detecting Session Handling Bugs with Static Analysis and Team Standards

Manually checking hundreds of controllers makes it easy to miss a session bug. Static analysis can detect missing session validations, loose type comparisons, and unhandled array keys before deployment.

Our guide to PHPStan on legacy code explains how static analyzers trace variable types through branches without running the code. Typed accessors can give the analyzer a way to check session values at the boundary.

For example, a typed repository call can expose an unchecked session value:

// Validate and cast the value before passing it to a typed API.
$userId = $_SESSION['user_id'];
$user = $repository->find($userId); // Error: Parameter #1 $id expects int, mixed given.

Use typed helper functions or session value objects to check that values from $_SESSION have the expected scalar types.

Write down the session conventions as well. New hires and junior developers need to know why a raw session_destroy() call is insufficient. Document these conventions clearly across onboarding checklists, pull request guidelines, and incident procedures so the team can follow them consistently.

Common Session Security Mistakes

Session bugs also turn up in code written by experienced teams. Check for these mistakes during review:

1. Binding Sessions to IP Addresses

Binding a session to $_SERVER['REMOTE_ADDR'] means invalidating it whenever the user's IP address changes. That can break legitimate sessions: mobile devices switch addresses between cellular towers and Wi-Fi, and corporate proxy clusters may use different outgoing addresses for consecutive requests. A safer approach is to bind sessions to stable user-agent characteristics or request multi-factor re-authentication when geographic velocity anomalies occur.

A widescreen diagnostics monitor highlights erratic network location routing flagged with a warning cross beside a resilient authenticated session conduit.

2. Storing Unencrypted Sensitive Data in Session Payloads

Session payloads on disk or in Redis contain serialized PHP data, which is not encrypted by default. Plaintext credit card numbers, encryption keys, and unhashed authentication tokens become exposed if someone compromises the storage backend or obtains an unencrypted backup. Keep only the identity data you need, such as user primary keys and role identifiers, in $_SESSION. Fetch detailed profile attributes from encrypted database tables when needed.

3. Relying on Session Garbage Collection Probability

PHP's default cleanup uses session.gc_probability and session.gc_divisor to decide whether a session start triggers garbage collection. Check the effective values, because distributions can override them. If you disable request-driven collection, schedule cleanup for the actual storage backend and verify that expired records are removed.

4. Forgetting session_write_close Before Redirects

After a form submission, a Location: redirect can race with the session write if the endpoint neither calls session_write_close() nor exits immediately. The browser may follow the redirect before the script finishes writing to disk, so the destination page reads stale state. Call session_write_close() or exit immediately after a redirect header:

$_SESSION['flash_message'] = 'Profile updated.';
session_write_close();
header('Location: /account');
exit;