← Back to all snippets
PHP

Secure Cookie Configuration in PHP (HTTPOnly, Secure, SameSite)

Enhance web application security by properly configuring session and authentication cookies with HTTPOnly, Secure, and SameSite flags in PHP to mitigate common attacks.

<?php
// --- RECOMMENDED CONFIGURATION FOR SESSION COOKIES ---
// Make sure to call session_start() *after* setting session cookie parameters.
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1); // Set to 1 in production with HTTPS
ini_set('session.cookie_samesite', 'Lax'); // Can be 'Lax' or 'Strict'

session_start();

// --- EXAMPLE FOR CUSTOM COOKIES (e.g., "remember me" token) ---
function setSecureCookie(
    $name,
    $value,
    $expire = 0,
    $path = '/',
    $domain = '',
    $secure = true, // Set to true for HTTPS only
    $httponly = true, // Prevent client-side script access
    $samesite = 'Lax' // 'Lax' or 'Strict'
) {
    $options = [
        'expires' => $expire,
        'path' => $path,
        'domain' => $domain,
        'secure' => $secure,
        'httponly' => $httponly,
        'samesite' => $samesite,
    ];

    // PHP 7.3+ supports the $options array
    if (PHP_VERSION_ID >= 70300) {
        setcookie($name, $value, $options);
    } else {
        // Fallback for older PHP versions, 'samesite' won't be explicitly set
        setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
        // Manually add SameSite header if possible, or rely on other CSRF protection
        header("Set-Cookie: {$name}={$value}; Expires=" . gmdate('D, d-M-Y H:i:s T', $expire) . "; Max-Age=" . ($expire - time()) . "; Path={$path}" . ($domain ? "; Domain={$domain}" : '') . ($secure ? "; Secure" : '') . ($httponly ? "; HttpOnly" : '') . "; SameSite={$samesite}", false);
    }
}

// Usage example:
// User login successful
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';

// Set a custom secure cookie for "remember me" (careful with long expiration)
// The actual token should be a securely generated, unique, single-use token tied to the user
$rememberMeToken = bin2hex(random_bytes(32));
setSecureCookie('remember_token', $rememberMeToken, time() + (86400 * 30), '/', '', true, true, 'Lax'); // 30 days

echo "Session started and secure cookies configured.";
How it works: This PHP snippet demonstrates how to configure cookies securely, which is crucial for protecting user sessions and data. It focuses on three key attributes: `HttpOnly` (prevents client-side JavaScript from accessing the cookie, mitigating XSS risks), `Secure` (ensures the cookie is only sent over HTTPS, preventing eavesdropping), and `SameSite` (helps prevent Cross-Site Request Forgery (CSRF) attacks by restricting when the browser sends cookies with cross-site requests). The snippet shows both configuration for session cookies via `ini_set` and a custom function `setSecureCookie` for other application-specific cookies.

Need help integrating this into your project?

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

Hire DigitalCodeLabs