Cookies Demo

How Cookies Work

Cookies are small pieces of data stored by the browser and automatically sent with every request to the same domain.

Browser Server | | |---- GET /page.php ---------------->| | | setcookie('username', 'alice') |<--- Set-Cookie: username=alice ----| | | | [Browser stores cookie] | | | |---- GET /other.php --------------->| | Cookie: username=alice | <-- Sent automatically! | | $_COOKIE['username'] == 'alice' |<--- Welcome, Alice! ---------------|
Key characteristics:

Try It: Set a Cookie

Demo Pages

Setting Cookies in PHP

<?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
]);
?>
Important: setcookie() must be called before any output (HTML, whitespace, etc.) because cookies are sent in HTTP headers.

Reading Cookies in PHP

<?php
// Cookies arrive in $_COOKIE superglobal
$username = $_COOKIE['username'] ?? 'Guest';
$theme = $_COOKIE['theme'] ?? 'light';

echo "Hello, " . htmlspecialchars($username);
echo "Your theme: " . htmlspecialchars($theme);
?>

Deleting Cookies

<?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' => '/'
]);
?>

Cookie Security Flags

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)

Viewing Cookies in Browser

Open your browser's Developer Tools (F12) and look at:


Previous: URL Parameters | Next: Server Sessions