Last updated: August 26, 2026.
Call setcookie() before sending any response body. For authentication, store an opaque session identifier rather than personal data or credentials in the cookie.
<?php
setcookie('preferences', 'compact', [
'expires' => time() + 30 * 86400,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);Read and delete
<?php
$preference = (string) ($_COOKIE['preferences'] ?? 'default');
setcookie('preferences', '', [
'expires' => time() - 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);Cookie values are controlled by the browser and must be validated. Use SameSite=Strict where cross-site navigation is unnecessary and SameSite=None; Secure only when cross-site use is intentional.