Lesson 5 of 8
Cookies - Storage, Attributes & Security
Cookies are small pieces of data stored in the browser and sent with every request. They persist between browser sessions (unlike sessions which are server-side). Use cookies for: remembering user preferences, 'remember me' tokens, and analytics. Never store sensitive data like passwords or PII in cookies.
Setting & Reading Cookies Securely
<?php
declare(strict_types=1);
// ── Setting cookies ────────────────────────────────────────────
// setcookie(name, value, options_array) - PHP 7.3+ style (preferred)
setcookie("theme", "dark", [
"expires" => time() + (30 * 24 * 3600), // 30 days
"path" => "/", // available site-wide
"domain" => "example.com", // only for this domain
"secure" => true, // HTTPS only
"httponly" => true, // no JS access
"samesite" => "Strict", // CSRF protection: Strict|Lax|None
]);
// ── Remember Me token (secure implementation) ──────────────────
function setRememberMeToken(int $userId): void {
// Generate cryptographically secure random token
$token = bin2hex(random_bytes(32)); // 64-char hex string
$expires = time() + (30 * 24 * 3600); // 30 days
// Store HASHED token in DB - never store raw token
$hashedToken = hash("sha256", $token);
// saveRememberToken($userId, $hashedToken, $expires); // DB call
setcookie("remember_token", $token, [
"expires" => $expires,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Strict",
]);
}
function checkRememberMeToken(): ?int {
if (!isset($_COOKIE["remember_token"])) return null;
$token = $_COOKIE["remember_token"];
$hashedToken = hash("sha256", $token);
// Find user by hashed token in DB
// $user = findUserByRememberToken($hashedToken);
// Validate token not expired (check expiry in DB)
// if ($user && $user["token_expires"] > time()) return $user["id"];
return null;
}
// ── Reading cookies ────────────────────────────────────────────
$theme = $_COOKIE["theme"] ?? "light"; // default if not set
$allowed = ["light", "dark", "system"];
$theme = in_array($theme, $allowed, true) ? $theme : "light"; // allowlist
// ── Deleting cookies ──────────────────────────────────────────
setcookie("remember_token", "", [
"expires" => time() - 3600, // past time = browser deletes it
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Strict",
]);
// ── Cookies vs Sessions ──────────────────────────────────────
// Sessions: server-side storage, expires with browser (by default), more secure
// Cookies: browser-side storage, persist for days/months, size-limited (4KB)
// Use sessions for: auth state, temp data, shopping cart (per visit)
// Use cookies for: preferences (theme), remember-me tokens, analytics IDsQuick Quiz
Tip
Tip
Practice Cookies Storage Attributes Security in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Cookies - Storage, Attributes & Security
Practice Task
Note
Practice Task - (1) Write a working example of Cookies Storage Attributes Security from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Cookies Storage Attributes Security is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?