PHP

Secure Session Bootstrap

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Start a session with all the security flags you should always set: HttpOnly, SameSite=Strict, Secure on HTTPS, custom name, and an idle-timeout regeneration.
PHP
Raw
<?php
function startSecureSession(int $maxIdleSec = 1800): void {
    if (session_status() !== PHP_SESSION_NONE) return;

    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/',
        'domain'   => '',
        'secure'   => !empty($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
    session_name('app');
    session_start();

    if (isset($_SESSION['_last']) && time() - $_SESSION['_last'] > $maxIdleSec) {
        // Idle too long → kill the session, prevent fixation.
        session_unset(); session_destroy(); session_start();
    }
    $_SESSION['_last'] = time();
}

startSecureSession();
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.