Because the HTTP protocol is inherently stateless, the web server does not inherently know whether two requests come from the exact same person. To recognize returning visitors, remember user preferences (such as dark mode vs light mode), or retain shopping carts, websites use Cookies. In PHP, cookies are created on the server and transmitted to the client's web browser via HTTP response headers.
Figure 5: The lifecycle and architecture of Client-Side Cookies vs Server-Side PHP Sessions.
setcookie()In PHP, you create or modify a cookie using the setcookie() function:
setcookie(name, value, expire, path, domain, secure, httponly);
"theme")."dark").time() + 3600 * 24 * 30 for 30 days). Omitting this makes it a session cookie (deleted when the browser closes)."/" makes it available across your entire website).true, the cookie is transmitted only over encrypted HTTPS connections.true, prevents JavaScript from accessing the cookie via document.cookie, effectively blocking XSS cookie theft!<?php
// Step 1: Set cookie (MUST be before any HTML output!)
$cookieName = "preferred_theme";
$cookieValue = "dark_mode";
$expirationTime = time() + (86400 * 30); // 86400 seconds = 1 day * 30 days
// Modern PHP 7.3+ Options Array Syntax (Cleanest & Most Secure):
setcookie($cookieName, $cookieValue, [
'expires' => $expirationTime,
'path' => '/',
'secure' => true, // Transmit over HTTPS only
'httponly' => true, // Inaccessible to JavaScript (XSS Protection)
'samesite' => 'Lax' // CSRF Protection
]);
?>
<!-- Step 2: Reading the cookie on subsequent page visits -->
<!DOCTYPE html>
<html>
<body>
<?php
if (isset($_COOKIE["preferred_theme"])) {
echo "Active Theme: " . htmlspecialchars($_COOKIE["preferred_theme"]);
} else {
echo "Default Theme (Light Mode)";
}
?>
</body>
</html>
You cannot delete a cookie directly from server memory because the cookie file resides on the client's machine. To delete a cookie, you instruct the user's browser to discard it by setting its expiration date to a time in the past:
<?php
// Set expiration date to one hour ago (time() - 3600)
setcookie("preferred_theme", "", time() - 3600, "/");
echo "Cookie 'preferred_theme' has been successfully deleted.";
?>
High-Frequency Exam Question:
Q: Why should sensitive data like user passwords never be stored in cookies?
A: Cookies reside in plain text files on the user's local hard drive and are transmitted across the internet with every request. Anyone with physical access to the device or network packet inspection tools could read or modify the cookie. Always store sensitive data in Server-Side Sessions.
Exercise 26.1: Create a visit counter using cookies that tracks how many times a user has refreshed the page during the last 24 hours.
Exercise 26.2: Write a script that checks if cookies are enabled in the visitor's browser using count($_COOKIE) > 0 after a test cookie is set.