PHP Cookies

A cookie is a small value stored in the visitor's browser and sent back with every request to your site.

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

Like sessions, setcookie() must be called before any output, because it sends an HTTP header.

PHP
<?php
  $theme = $_COOKIE['theme'] ?? 'light';

A cookie you just set is not in $_COOKIE on the same request — it only appears on the next one, because the browser has to send it back.

Set it to an already-past expiry, with the same path and domain:

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

Cookies vs sessions

Cookie Session
Stored in the browser on the server
Visible to user yes, fully editable only the id
Size limit ~4 KB unlimited
Survives browser close if you set an expiry usually not
Safe for trust decisions no yes

The rule that matters

Anything in a cookie can be edited by the visitor. This is a catastrophic bug:

PHP
<?php
  // NEVER
  if ($_COOKIE['is_admin'] === '1') {
      // anyone can set this in their browser console
  }

Store an identifier in the session, and read permissions from the database:

PHP
<?php
session_start();
$user = findUser($_SESSION['user_id'] ?? 0);
if ($user && $user['role'] === 'admin') {
    // safe — the server decided this
}

Cookies are fine for genuinely low-stakes preferences: theme, language, "hide this banner", a guest cart token.