Skip to content

PHP Tutorial Superglobals

$_COOKIE

Lesson 151 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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.

index.php
PHP
<?php
// A cookie named "theme" with the value "dark" was sent by the browser
echo $_COOKIE["theme"] ?? "light";

Reading with a default

index.php
PHP
<?php
$_COOKIE = ["theme" => "dark"];

$theme = $_COOKIE["theme"] ?? "light";
$lang = $_COOKIE["lang"] ?? "en";

echo "$theme / $lang";
Output
OUTPUT
dark / en

setcookie() sends a header to the browser. The cookie appears in $_COOKIE only on the next request.

index.php
PHP
<?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.
index.php
PHP
<?php
$_COOKIE = ["theme" => "neon<script>"];

$allowed = ["light", "dark"];
$theme = in_array($_COOKIE["theme"] ?? "", $allowed, true) ? $_COOKIE["theme"] : "light";

echo $theme;
Output
OUTPUT
light

Cookies vs sessions

CookieSession
StoredIn the browserOn the server (browser keeps an ID)
Visitor can editYesNo
Good forPreferences (theme, language)Login state, cart, anything private

Details are in Sessions vs Cookies.

lightbulb
Consent matters
Preference cookies are usually fine. Tracking and analytics cookies may need the visitor’s consent depending on where your visitors live. Check the rules that apply to your site.