PHP
Set Secure and HTTPOnly Cookies with SameSite Attribute
Enhance session security by setting cookies with `Secure`, `HTTPOnly`, and `SameSite` attributes to prevent XSS, CSRF, and interception over insecure channels.
// For a session cookie (example)
session_set_cookie_params([
'lifetime' => 3600, // 1 hour
'path' => '/',
'domain' => 'yourdomain.com', // Replace with your domain
'secure' => true, // Only send over HTTPS
'httponly' => true, // Prevent JavaScript access
'samesite' => 'Lax' // Protect against CSRF
]);
session_start();
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john.doe';
// For a custom persistent cookie (example)
$cookie_name = 'user_preference';
$cookie_value = 'dark_mode';
setcookie(
$cookie_name,
$cookie_value,
[
'expires' => time() + (86400 * 30), // 30 days
'path' => '/',
'domain' => 'yourdomain.com', // Replace with your domain
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]
);
How it works: This PHP snippet demonstrates how to set cookies with critical security attributes. The `secure` attribute ensures cookies are only sent over HTTPS. `httponly` prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks. The `samesite` attribute (e.g., `Lax` or `Strict`) helps protect against Cross-Site Request Forgery (CSRF) attacks by controlling when cookies are sent with cross-site requests. Setting these attributes for both session and custom cookies significantly hardens your application's session management.