Web Security
Beginner
1 min read
SameSite Cookies: Browser-Enforced CSRF Protection
Example
<?php
// PHP: setting a hardened session cookie
session_set_cookie_params([
'lifetime' => 0, // expire when browser closes
'path' => '/',
'domain' => 'example.com',
'secure' => true, // HTTPS only
'httponly' => true, // no JavaScript access
'samesite' => 'Lax', // CSRF protection; use 'Strict' for high-security apps
]);
session_start();
// Or set an arbitrary cookie:
setcookie('user_pref', 'dark_mode', [
'expires' => time() + 86400 * 30,
'path' => '/',
'secure' => true,
'httponly' => false, // needs to be JS-readable? only if necessary
'samesite' => 'Lax',
]);
// Laravel config/session.php equivalents:
// 'secure' => env('SESSION_SECURE_COOKIE', true),
// 'http_only' => true,
// 'same_site' => 'lax',
// ----------------------------------------------------------------
// Set-Cookie header examples (what the browser receives):
// ----------------------------------------------------------------
// Session cookie (most secure):
// Set-Cookie: session=abc123; Path=/; Secure; HttpOnly; SameSite=Strict
//
// Third-party/embedded widget cookie (cross-site allowed):
// Set-Cookie: widget_token=xyz; Path=/; Secure; SameSite=None
// (Note: SameSite=None REQUIRES Secure — browsers reject it otherwise)
Related Resources
Web Security Reference
Complete tag & property list
Web Security How-To Guides
Step-by-step practical guides
Web Security Exercises
Practice what you've learned
More in Web Security