PHP

Configure Secure and HttpOnly Cookies for Enhanced Session Security

Strengthen web application security by setting HttpOnly and Secure flags on session cookies, protecting against XSS attacks and interception over insecure connections.

<?php
// Recommended secure session configuration for PHP
ini_set('session.cookie_httponly', 1); // Prevent JavaScript access to cookies
ini_set('session.cookie_secure', 1);   // Only send cookies over HTTPS
ini_set('session.cookie_samesite', 'Lax'); // Protect against CSRF

// Optionally set session cookie lifetime (e.g., 1 hour)
ini_set('session.cookie_lifetime', 3600);

// Ensure session starts after configuration
session_start();

// Example of setting a custom cookie with these flags
// (session_start() handles these for the session cookie automatically if ini_set is used)
$cookie_name = "user_preference";
$cookie_value = "dark_mode";
$expiration = time() + (86400 * 30); // 30 days
$path = "/";
$domain = $_SERVER['HTTP_HOST']; // Or specify a fixed domain
$secure = true; // Only send over HTTPS
$httponly = true; // Prevent JavaScript access
$samesite = 'Lax'; // 'Lax', 'Strict', or 'None' (requires secure=true)

// PHP 7.3+ setcookie with options array
setcookie($cookie_name, $cookie_value, [
    'expires' => $expiration,
    'path' => $path,
    'domain' => $domain,
    'secure' => $secure,
    'httponly' => $httponly,
    'samesite' => $samesite
]);

// For older PHP versions (before 7.3), samesite needs to be appended to the path/domain arguments
// setcookie($cookie_name, $cookie_value, $expiration, $path . '; SameSite=' . $samesite, $domain, $secure, $httponly);

echo "Secure cookie settings applied and session started.";
?>
How it works: This snippet demonstrates how to configure secure cookie settings, specifically for session cookies, using PHP. By setting `session.cookie_httponly` to `1`, cookies become inaccessible to client-side JavaScript, mitigating the risk of session hijacking via Cross-Site Scripting (XSS) attacks. Setting `session.cookie_secure` to `1` ensures cookies are only sent over HTTPS connections, protecting them from interception on insecure networks. The `SameSite` attribute further enhances CSRF protection. These configurations significantly strengthen the security posture of web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs