iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Cookies

Cookies are key/value pairs stored in the browser and sent back with every request. PHP reads them from $_COOKIE and writes them with setcookie().

Set

PHP
setcookie(
    name: 'theme',
    value: 'dark',
    expires_or_options: time() + 60 * 60 * 24 * 30,   // 30 days
    path: '/',
    domain: '',
    secure: true,
    httponly: true,
);

Read

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

The cookie you just setcookie()d isn't in $_COOKIE until the next request — the browser must send it back first.

Delete

PHP
setcookie('theme', '', time() - 3600, '/');   // expired in the past

The flags that matter

FlagWhy
secure: trueOnly sent over HTTPS.
httponly: trueJS can't read it (mitigates XSS-driven theft).
samesite: 'Lax' / 'Strict'Stops cookies from going on cross-site requests (mitigates CSRF).
path: '/'Where on your site it applies.
domain: '.example.com'Share across subdomains.

Modern signature

From PHP 7.3 you can pass an options array — cleaner with named arguments:

PHP
setcookie('sid', $value, [
    'expires'  => time() + 86400,
    'path'     => '/',
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

Don't put secrets in cookies

Cookies live in the browser and travel with every request. For login state and similar, store a random session ID in the cookie and keep the real data server-side in a session (next lesson).

Tip: Cookie headers must be sent before any output. If you've already echoed HTML, setcookie() warns and does nothing. Use output buffering or set cookies first thing.

Example

Example
<?php
setcookie('theme', 'dark', time() + 3600 * 24 * 30, '/');
echo $_COOKIE['theme'] ?? 'no cookie yet';
Try it Yourself »

Exercise

Set a cookie with…

('theme', 'dark', time() + 3600);

Test yourself

Q1. Cookies the browser will send back appear in…
Q2. HttpOnly flag stops…
Q3. setcookie() must run…

Discussion

Loading…