Skip to content

PHP Tutorial Sessions and Cookies

Setting Cookies

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

setcookie() tells the browser to store a cookie. The modern way uses an options array.

index.php
PHP
<?php
setcookie("theme", "dark", [
    "expires" => time() + 60 * 60 * 24 * 30,   // 30 days
    "path" => "/",
    "secure" => true,       // HTTPS only
    "httponly" => true,     // hidden from JavaScript
    "samesite" => "Lax",
]);

Call it before any output

Cookies are sent in the HTTP headers, so setcookie() must run before any output, just like session_start() and header(). Otherwise PHP warns “headers already sent”, and the cookie is not sent.

The options

OptionMeaning
expiresA Unix timestamp. 0 means “until the browser closes”
pathWhere the cookie applies. "/" for the whole site
domainUsually leave out
securetrue sends only over HTTPS
httponlytrue blocks JavaScript access
samesite"Lax", "Strict" or "None" (None needs secure)

The cookie goes to the browser with the response. PHP fills $_COOKIE from the request. So the new cookie appears in $_COOKIE only on the next page load.

index.php
PHP
<?php
setcookie("seen", "yes", ["path" => "/"]);

var_dump(isset($_COOKIE["seen"]));   // false on the first visit

If you need the value now, store it in a variable too.

Time helpers

index.php
PHP
<?php
$expires = time() + 60 * 60 * 24 * 7;   // 7 days from now

echo round(($expires - time()) / 86400) . " days";
Output
OUTPUT
7 days

Encode values

setcookie() URL-encodes the value for you. setrawcookie() does not, so avoid it unless you know why you need it.

Choose the right SameSite value

  • Lax is a good default: cookies are sent when the user clicks a link to your site, but not on most cross-site requests.
  • Strict is stronger, but a cookie is not sent when someone arrives from another site by a link. A user opening your site from an email can appear logged out.
  • None sends the cookie in all cross-site requests. It requires secure => true.
index.php
PHP
<?php
function themeFromCookie(array $cookies): string
{
    $allowed = ["light", "dark"];

    return in_array($cookies["theme"] ?? "", $allowed, true) ? $cookies["theme"] : "light";
}

echo themeFromCookie(["theme" => "dark"]) . " ";
echo themeFromCookie(["theme" => "<script>"]);
Output
OUTPUT
dark light
dangerous
Do not put secrets in a cookie
A cookie value is visible and editable by the visitor. For anything that grants access, use a session, or a long random token that you verify on the server.