PHP cookies: set, read and delete safely

Beginner  Nov 3, 2026

Small values stored in the browser, and the flags that make them safer.

PHP cookies: set, read and delete safely
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Set a cookie

<?php
setcookie('theme', 'dark', [
    'expires'  => time() + 60 * 60 * 24 * 30,   // 30 days
    'path'     => '/',
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

Call setcookie() before any HTML output.

How the code in this section fits into the page.
How the code in this section fits into the page.

Read it

$theme = $_COOKIE['theme'] ?? 'light';

The cookie is available on the next request, not the one that set it.

Delete it

Set an expiry date in the past:

setcookie('theme', '', ['expires' => time() - 3600, 'path' => '/']);

What the flags do

  • httponly: JavaScript cannot read the cookie, which limits damage from XSS.
  • secure: only sent over HTTPS.
  • samesite: limits sending the cookie with requests from other sites.
The main points of this section.
The main points of this section.

Rules

  • Never trust a cookie value. The visitor can edit it.
  • Do not put passwords or private data in cookies.
  • For login state use sessions, not custom cookies.
The main points of this section.
The main points of this section.

More tutorials