PHP Cookies

PHP Cookies

Cookies are small key-value pairs stored in the user's browser. PHP sends them with setcookie() and reads them via $_COOKIE.

1 - Setting a Cookie

setcookie("username", "Alice", time() + 3600);        // 1 hour
setcookie("theme",    "dark",  time() + 86400 * 30);  // 30 days

2 - Reading

if (isset($_COOKIE["username"])) {
    echo "Welcome back, " . htmlspecialchars($_COOKIE["username"]);
}

3 - Deleting

setcookie("username", "", time() - 3600); // expiry in the past

4 - Secure Options

setcookie(
    name:     "session_token",
    value:    $token,
    expires:  time() + 3600,
    path:     "/",
    domain:   "",
    secure:   true,   // HTTPS only
    httponly: true    // not accessible via JavaScript
);

5 - SameSite Attribute (PHP 7.3+)

setcookie("csrf_token", $token, [
    "expires"  => time() + 3600,
    "path"     => "/",
    "secure"   => true,
    "httponly" => true,
    "samesite" => "Strict"  // or "Lax"
]);

Note: Cookies must be set before any HTML is sent. Call setcookie() at the very top of your PHP file, before any echo or HTML output.

-Tip-