A cookie is a small piece of text that the browser stores and sends back with every request to your site. $_COOKIE holds the cookies that came with the current request.
<?php
// A cookie named "theme" with the value "dark" was sent by the browser
echo $_COOKIE["theme"] ?? "light";
Reading with a default
<?php
$_COOKIE = ["theme" => "dark"];
$theme = $_COOKIE["theme"] ?? "light";
$lang = $_COOKIE["lang"] ?? "en";
echo "$theme / $lang";
dark / en
Setting a cookie does not fill $_COOKIE right away
setcookie() sends a header to the browser. The cookie appears in $_COOKIE only on the next request.
<?php
setcookie("theme", "dark", [
"expires" => time() + 86400 * 30,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax",
]);
// $_COOKIE["theme"] is not set yet in this request
Cookies are untrusted
The browser owner can see and edit every cookie. Treat the value like any other input:
- Validate it against what you expect.
- Escape it before printing.
- Never store a price, a role or a “logged in” flag in a plain cookie. Someone will change it.
<?php
$_COOKIE = ["theme" => "neon<script>"];
$allowed = ["light", "dark"];
$theme = in_array($_COOKIE["theme"] ?? "", $allowed, true) ? $_COOKIE["theme"] : "light";
echo $theme;
light
Cookies vs sessions
| Cookie | Session | |
|---|---|---|
| Stored | In the browser | On the server (browser keeps an ID) |
| Visitor can edit | Yes | No |
| Good for | Preferences (theme, language) | Login state, cart, anything private |
Details are in Sessions vs Cookies.