Cookies are small pieces of data stored by the browser and automatically sent with every request to the same domain.
<?php
// Basic cookie - expires when browser closes
setcookie('username', 'alice');
// Cookie that lasts 30 days
setcookie('theme', 'dark', time() + (30 * 24 * 60 * 60));
// Secure cookie with all options
setcookie('session_id', 'abc123', [
'expires' => time() + 3600, // 1 hour
'path' => '/', // Available site-wide
'domain' => '', // Current domain only
'secure' => true, // HTTPS only
'httponly' => true, // No JavaScript access
'samesite' => 'Lax' // CSRF protection
]);
?>
setcookie() must be called before any output (HTML, whitespace, etc.) because cookies are sent in HTTP headers.
<?php // Cookies arrive in $_COOKIE superglobal $username = $_COOKIE['username'] ?? 'Guest'; $theme = $_COOKIE['theme'] ?? 'light'; echo "Hello, " . htmlspecialchars($username); echo "Your theme: " . htmlspecialchars($theme); ?>
<?php
// To delete, set expiration in the past
setcookie('username', '', time() - 3600);
// Or with all the same options it was set with
setcookie('theme', '', [
'expires' => time() - 3600,
'path' => '/'
]);
?>
| Flag | Purpose |
|---|---|
HttpOnly |
Cookie cannot be accessed by JavaScript (protects against XSS) |
Secure |
Cookie only sent over HTTPS connections |
SameSite |
Controls cross-site cookie sending (Strict, Lax, None) |
Open your browser's Developer Tools (F12) and look at: