PHP

Secure PHP Session Cookies with HttpOnly, Secure, and SameSite Flags

Configure your PHP session cookies with HttpOnly, Secure, and SameSite flags to prevent XSS-related cookie theft and CSRF attacks, enhancing session security.

<?php
/**
 * Configures PHP session cookies for enhanced security.
 * Call this before session_start().
 *
 * @param bool $secure True if cookies should only be sent over HTTPS.
 * @param bool $httponly True if cookies should not be accessible via client-side scripts.
 * @param string $samesite Controls when cookies are sent with cross-site requests (Lax, Strict, None).
 * @param string $path Path on the domain where the cookie will work.
 * @param string $domain The domain that the cookie is available to.
 */
function configureSecureSessionCookies(
    bool $secure = true,
    bool $httponly = true,
    string $samesite = 'Lax', // or 'Strict' for higher security, 'None' with 'Secure' for cross-site
    string $path = '/',
    string $domain = '' // Leave empty for current domain, or specify 'yourdomain.com'
): void {
    // Get current cookie parameters to maintain existing settings
    $params = session_get_cookie_params();

    session_set_cookie_params([
        'lifetime' => $params['lifetime'], // Or set a specific lifetime like 0 for browser close
        'path' => $path,
        'domain' => $domain,
        'secure' => $secure,       // Only send cookie over HTTPS
        'httponly' => $httponly,   // Prevent JavaScript access to cookie
        'samesite' => $samesite    // Mitigate CSRF and other cross-site attacks
    ]);

    // Regenerate session ID on login or privilege escalation to prevent session fixation
    // if (session_status() === PHP_SESSION_ACTIVE && $_SESSION['authenticated_just_now']) {
    //     session_regenerate_id(true);
    //     unset($_SESSION['authenticated_just_now']);
    // }
}

// --- Usage Example ---
// 1. Call this function *before* session_start()
configureSecureSessionCookies(
    secure: true,      // Set to true in production for HTTPS only
    httponly: true,    // Always true for session IDs
    samesite: 'Lax'    // 'Strict' if no cross-site requests should send session cookies
);

// 2. Start the session
session_start();

// Store a value in the session
if (!isset($_SESSION['views'])) {
    $_SESSION['views'] = 0;
}
$_SESSION['views']++;

echo "Session ID (should not be in JS): " . session_id() . "
";
echo "Page views: " . $_SESSION['views'] . "
";
echo "Check your browser's dev tools for cookie flags (HttpOnly, Secure, SameSite).
";
?>
How it works: This PHP snippet demonstrates how to configure session cookies for enhanced security using `session_set_cookie_params()`. Setting `secure` to `true` ensures cookies are only sent over HTTPS. `httponly` set to `true` prevents client-side JavaScript from accessing the session cookie, mitigating XSS-related cookie theft. The `samesite` attribute (e.g., 'Lax' or 'Strict') helps prevent Cross-Site Request Forgery (CSRF) by controlling when cookies are sent with cross-site requests. Call this function before `session_start()` for effective implementation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs