setcookie(), $_COOKIE, Security Flags)Cookies are small data files stored by the client web browser at the request of the server. Cookies persist state across web requests and are transmitted back to the server in HTTP headers.
setcookie() Parameterssetcookie(
string $name,
string $value = "",
int $expires_or_options = 0,
string $path = "",
string $domain = "",
bool $secure = false,
bool $httponly = false
): bool
flowchart LR
A["Server Calls setcookie()"] --> B["Set-Cookie Header Sent in HTTP Response"]
B --> C["Browser Stores Cookie Locally"]
C --> D["Browser Attaches Cookie to Future Requests"]
D --> E["PHP Reads Cookie in $_COOKIE Array"]
<?php
declare(strict_types=1);
// 1. Setting a Secure Cookie (Expires in 30 Days)
$cookieName = "theme_preference";
$cookieValue = "dark_mode";
$expiration = time() + (86400 * 30); // 30 days
setcookie($cookieName, $cookieValue, [
'expires' => $expiration,
'path' => '/',
'domain' => '',
'secure' => true, // Sent over HTTPS only
'httponly' => true, // Inaccessible via JavaScript document.cookie (Mitigates XSS)
'samesite' => 'Lax' // Protection against CSRF attacks
]);
// 2. Reading Cookie in Subsequent Requests
$currentTheme = $_COOKIE[$cookieName] ?? 'light_mode';
// 3. Deleting a Cookie (Set Expiration Date in the Past)
function deleteThemeCookie(string $name): void
{
setcookie($name, '', time() - 3600, '/');
unset($_COOKIE[$name]);
}
echo "Current Theme Preference: " . htmlspecialchars($currentTheme) . "
";
httponly => true on All Sensitive Cookies: Prevents client-side XSS scripts from reading session and auth cookies via document.cookie.secure => true in Production: Enforces cookie transmission over encrypted HTTPS channels only.samesite => 'Lax' or 'Strict': Protects cookies against Cross-Site Request Forgery (CSRF) exploits.Write a setcookie() call that sets a user_lang cookie to "en" expiring in 7 days with httponly set to true!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.