A cookie is a small piece of data stored in the browser and sent back to the server with every request.
Create a cookie
setcookie('theme', 'dark', [
'expires' => time() + 60 * 60 * 24 * 30, // 30 days
'path' => '/',
'secure' => true, // HTTPS only
'httponly' => true, // JavaScript cannot read it
'samesite' => 'Lax',
]);
setcookie() must run before any output.
Read
$theme = $_COOKIE['theme'] ?? 'light';
A new cookie appears in $_COOKIE only on the next request.
Delete
Set the expiry in the past: setcookie('theme', '', time() - 3600, '/');
Good uses
Remember language, theme, "remember me" tokens, recently viewed items.
Do not store
Passwords or anything secret — users can see and edit cookies. Size limit is about 4 KB per cookie.
In India and the EU, tell users about non-essential cookies (consent banner).
Example
<?php
$allowed = ['en' => 'English', 'hi' => 'हिन्दी'];
if (isset($_GET['lang']) && isset($allowed[$_GET['lang']])) {
setcookie('lang', $_GET['lang'], [
'expires' => time() + 60 * 60 * 24 * 365,
'path' => '/',
'httponly' => true,
'samesite' => 'Lax',
]);
$_COOKIE['lang'] = $_GET['lang']; // use it on this request too
}
if (isset($_GET['forget'])) {
setcookie('lang', '', time() - 3600, '/');
unset($_COOKIE['lang']);
}
$lang = $_COOKIE['lang'] ?? 'en';
$greeting = $lang === 'hi' ? 'नमस्ते! आपका स्वागत है।' : 'Hello! Welcome.';
?>
<h3><?= $greeting ?></h3>
<p>Language: <?= $allowed[$lang] ?></p>
<a href="?lang=en">English</a> | <a href="?lang=hi">हिन्दी</a> | <a href="?forget=1">Forget</a>
Choose a language, close and reopen the page — the cookie remembers your choice for a year.