Enable PHP Session Strict Mode and Regenerate IDs Safely

Keep session.use_strict_mode enabled for normal application traffic. It makes PHP reject a session identifier that the active save handler does not recognize, reducing session-fixation risk. Regenerate the identifier after login or another privilege change.

Last updated: October 9, 2026.

<?php
declare(strict_types=1);

ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

session_start();

function markUserAuthenticated(int $userId): void
{
    if (!session_regenerate_id(true)) {
        throw new RuntimeException('Session ID regeneration failed.');
    }

    $_SESSION['user_id'] = $userId;
    $_SESSION['authenticated_at'] = time();
}

Set these options before session_start(). The secure cookie flag assumes the site is served only over HTTPS. Use server configuration for permanent settings when possible instead of repeating them in every request.

Why some session_create_id examples briefly disable strict mode

A specialized workflow may call session_create_id(), assign that newly generated value with session_id(), and then start the session. Strict mode can reject that value because it has not yet been initialized in storage. The example temporarily disables strict validation only while adopting its own generated ID, then restores it.

That exception is not a recommendation for ordinary login code. The PHP manual says session.use_strict_mode should be enabled for general session security. Most applications should let PHP create IDs and use session_regenerate_id() when privileges change.

Custom handlers must validate IDs too

Strict mode depends on the session save handler being able to determine whether an ID already exists. A custom handler must implement the appropriate ID-validation interface or callback; otherwise the configuration flag can be ineffective. Test this by sending a random session cookie and confirming that PHP replaces it.

The official session security guide also recommends timestamp-based expiration and careful regeneration behavior for concurrent requests. Continue with custom session ID generation, secure PHP cookies, and secure password hashing.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov