PHP

Set Cookie with Modern Options

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
PHP 7.3+ accepts an options array on setcookie() — use it. Sets HttpOnly, Secure on HTTPS, SameSite=Lax by default, and a sensible expiry.
PHP
Raw
<?php
function setSecureCookie(string $name, string $value, int $daysToLive = 30, string $sameSite = 'Lax'): bool {
    return setcookie($name, $value, [
        'expires'  => time() + ($daysToLive * 86400),
        'path'     => '/',
        'domain'   => '',
        'secure'   => !empty($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => $sameSite,   // Lax | Strict | None
    ]);
}

setSecureCookie('theme', 'dark', 365);
setSecureCookie('analytics_id', $id, 30, 'Lax');
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.