Start the session securely, expire authenticated state by timestamp, validate every state-changing POST, then regenerate the session ID before recording a successful login. Finish each POST with a 303 redirect so refreshing the destination does not submit the form again.
Last updated: November 23, 2026.
<?php
ini_set('session.use_strict_mode', '1');
session_set_cookie_params([
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
session_start();
$now = time();
if (isset($_SESSION['user_id'], $_SESSION['last_seen'])
&& $now - $_SESSION['last_seen'] > 600) {
unset($_SESSION['user_id'], $_SESSION['last_seen']);
$_SESSION['flash'] = 'Your session expired. Please sign in again.';
}
if (isset($_SESSION['user_id'])) {
$_SESSION['last_seen'] = $now;
}
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$token = (string) ($_POST['csrf'] ?? '');
if (!hash_equals($_SESSION['csrf'], $token)) {
http_response_code(400);
exit('Invalid request.');
}
if (verifyCredentials($_POST)) {
session_regenerate_id();
$_SESSION['user_id'] = currentUserId();
$_SESSION['last_seen'] = $now;
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
header('Location: /account.php', true, 303);
exit;
}The example assumes verifyCredentials() validates input and verifies the password. Keep password hashes outside the source file and never store them in the session.
Why this order matters
Cookie settings and session.use_strict_mode must be configured before session_start(). PHP’s session security guidance recommends strict mode, timestamps and ID regeneration when privileges increase. Expire authenticated state before using it; regenerate the ID before adding the authenticated user.
Validate CSRF tokens before every state-changing POST. SameSite cookies help, but sessions do not provide CSRF protection. Compare a random token with hash_equals() and rotate it after authentication changes.
Keep redirects and concurrent requests predictable
A 303 redirect implements Post/Redirect/Get: reload then repeats a GET, not the submitted action. Remove any flash message after displaying it once.
Do not call session_destroy() merely to expire one login when unrelated session state must survive. Remove the authentication keys instead. Native file sessions serialize requests using the same session, so after copying required values, close the session early.