How to set and read a cookie
Short answer
setcookie() sends a cookie, and the $_COOKIE array reads them on the next request:
<?php
setcookie('theme', 'dark', [
'expires' => time() + 60 * 60 * 24 * 30,
'path' => '/',
'httponly' => true,
'samesite' => 'Lax',
]);
$theme = $_COOKIE['theme'] ?? 'light';Removing
Send a cookie of the same name with a date in the past:
<?php
setcookie('theme', '', ['expires' => time() - 3600, 'path' => '/']);Two rules
Call setcookie() before any output to the page. And a cookie cannot be trusted: the visitor can change the value, so rights and prices are not kept in them.
Functions used in this recipe
- setcookie — Sends a cookie to the browser.
- time — Returns the current timestamp.
- htmlspecialchars — Replaces HTML special characters with safe entities.