PHP

Configure Secure Session Cookies in PHP

Learn how to configure PHP sessions to use secure, HTTP-only, and SameSite cookies, protecting user sessions from common attacks like XSS and CSRF.

<?php
// This should be called at the very beginning of your application,
// before any output is sent to the browser.

// 1. Set cookie parameters for the session
// session_set_cookie_params(int $lifetime, string $path, string $domain, bool $secure, bool $httponly)
// Set the session cookie to expire in 0 seconds when browser closes (or specify a lifetime)
$lifetime = 0; // Or specify a duration, e.g., 3600 for 1 hour
$path = '/';
$domain = ''; // Leave empty for current domain, or specify 'yourdomain.com'
$secure = true; // IMPORTANT: Only send cookie over HTTPS
$httponly = true; // IMPORTANT: Prevent client-side JavaScript access to the cookie

session_set_cookie_params([
    'lifetime' => $lifetime,
    'path' => $path,
    'domain' => $domain,
    'secure' => $secure,
    'httponly' => $httponly,
    // PHP 7.3+ introduces 'samesite' option
    'samesite' => 'Lax' // 'Lax' or 'Strict' for CSRF protection. 'None' requires secure=true.
                                // 'Lax' protects against some CSRF attacks while allowing user-initiated navigation.
]);

// 2. Set PHP configuration directives (optional, can also be in php.ini)
ini_set('session.use_only_cookies', 1); // IMPORTANT: Prevent session fixation attacks
ini_set('session.cookie_secure', ($secure ? 1 : 0)); // Ensure 'secure' is set for PHP session cookies
ini_set('session.cookie_httponly', ($httponly ? 1 : 0)); // Ensure 'httponly' is set
ini_set('session.cookie_samesite', 'Lax'); // Set SameSite for older PHP versions or as a fallback

// 3. Start the session
session_start();

// Regenerate session ID on login/privilege change to prevent session fixation
if (!isset($_SESSION['initiated'])) {
    session_regenerate_id(true); // true deletes the old session file
    $_SESSION['initiated'] = true;
}

// Example usage of session
if (!isset($_SESSION['views'])) {
    $_SESSION['views'] = 0;
}
$_SESSION['views']++;
echo "Page views: " . $_SESSION['views'] . "
";
?>
How it works: This PHP snippet configures secure session cookies to protect user sessions. By using `session_set_cookie_params()` and `ini_set()`, it ensures session cookies are marked as `Secure` (only sent over HTTPS), `HttpOnly` (inaccessible to client-side JavaScript, mitigating XSS), and `SameSite=Lax` (providing CSRF protection). Additionally, `session.use_only_cookies` prevents session fixation, and `session_regenerate_id(true)` upon session initiation or privilege changes further enhances security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs