1. The Need for State Management
The HTTP protocol is inherently stateless: each HTTP request is independent and has no memory of previous requests. To maintain logged-in user state, cart contents, and preferences, web applications use Cookies and Sessions.
2. PHP Cookies
A cookie is a small key-value pair stored on the client's browser. The browser transmits cookies back to the server in subsequent HTTP headers.
Setting and Reading Cookies:
$expireTime,
"path" => "/",
"secure" => true, // Transmit only over HTTPS
"httponly" => true, // Inaccessible to JavaScript (prevents XSS cookie theft)
"samesite" => "Strict" // CSRF protection
]);
// Reading a cookie on subsequent requests
if (isset($_COOKIE["preferred_theme"])) {
echo "Current theme preference: " . htmlspecialchars($_COOKIE["preferred_theme"]);
}
// Deleting a cookie: set expiration date in the past
setcookie("preferred_theme", "", time() - 3600, "/");
3. PHP Sessions
Unlike cookies which live on the client machine, session data resides securely on the server. The client only holds an opaque session identifier token (usually named PHPSESSID) inside a cookie.
Working with Sessions: