Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 147 ยท PHP and the Web

Cookies

Set, read and delete cookies in PHP with setcookie - expires, path, domain, secure, httponly and samesite - plus signed cookies and what never to store in one.

HTTP is stateless: every request arrives on its own, and the server has no built-in way to know that two requests came from the same browser. Cookies fill that gap. A cookie is a small named value that the server asks the browser to store; the browser then sends it back with every following request to that site. That's how a site remembers your language, your dark-mode preference, the items in a guest's basket, or (through a session ID) the fact that you're logged in.

In PHP you set cookies with setcookie() and read the ones the browser sent from $_COOKIE. Both are short calls, but the options matter a lot: they decide how long a cookie lives, which pages receive it, whether JavaScript can read it, and whether other sites can trigger requests that carry it. Getting them wrong is the root of several well-known attacks.

Our editor runs PHP on the command line, where there's no browser to store anything, so cookies can't really travel. The runnable examples simulate the exchange: they build the exact Set-Cookie headers a server sends, and model a browser that stores cookies and sends them back, so you can watch the whole round trip.

How cookies travel

A cookie exchange takes two HTTP messages. First the server's response includes a Set-Cookie header:

TEXT
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Set-Cookie: theme=dark; expires=Wed, 17 Nov 2027 12:00:00 GMT; Max-Age=34214400; path=/; secure; HttpOnly; SameSite=Lax

From then on, the browser adds a Cookie header to each request to the same site, containing the name and value only (never the options):

TEXT
GET /php/cookies HTTP/1.1
Host: example.com
Cookie: theme=dark; lang=de

PHP parses that header into $_COOKIE before your script runs, so $_COOKIE['theme'] is 'dark'. Two consequences follow:

  1. A cookie you set is not in $_COOKIE during the same request. It only appears on the next request, after the browser has stored it and sent it back.
  2. $_COOKIE contains whatever the browser sends, and a user (or attacker) can edit cookies freely. Treat every cookie value as untrusted input, just like form fields.

The modern form of setcookie() takes the name, the value and an options array (available since PHP 7.3):

PHP
<?php
setcookie('theme', 'dark', [
    'expires' => time() + 60 * 60 * 24 * 365,  // one year from now
    'path' => '/',                              // sent with every page of the site
    'domain' => '',                             // current host only
    'secure' => true,                           // only over HTTPS
    'httponly' => true,                         // invisible to JavaScript
    'samesite' => 'Lax',                        // not sent on most cross-site requests
]);

Because cookies are sent as HTTP headers, setcookie() must run before any output, just like header(). If anything has been printed already (even a space before <?php), you get the "Cannot modify header information - headers already sent" warning and the cookie is silently not set. HTTP Headers, Status Codes and Redirects explains that error. setcookie() returns false in that case, but true doesn't prove the browser accepted the cookie.

Here is what each option means:

Option Default Meaning
expires 0 Unix timestamp when the cookie expires. 0 makes a session cookie, deleted when the browser closes.
path current directory Only requests under this path receive the cookie. Use '/' for the whole site.
domain '' (current host) Set 'example.com' to share it with subdomains like shop.example.com. Leave empty for the tightest scope.
secure false Only send over HTTPS. Use true on every HTTPS site.
httponly false Hide the cookie from JavaScript (document.cookie), which protects it from theft through XSS.
samesite not sent 'Lax', 'Strict' or 'None': whether the cookie is sent on requests started by other sites.
partitioned false PHP 8.5+: the Partitioned attribute for third-party cookies isolated per top-level site (CHIPS). Requires secure.

What setcookie() sends

To see what those options turn into, this simulation builds the same header text that setcookie() produces, with a fixed "current time" so the output stays the same on every run:

PHP Building Set-Cookie headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second cookie has no expires, so it's a session cookie, and its value was URL-encoded because a raw ; would end the value early. setcookie() encodes values for you, and PHP decodes them again when filling $_COOKIE. (Use setrawcookie() only if you need to send an already-encoded value unchanged.) The third cookie's domain=example.com also sends it to every subdomain.

Browsers cap the lifetime of cookies set by the server (Chrome limits it to 400 days), and they also limit size: about 4 KB per cookie including the name, and a limited number of cookies per site. Cookies are sent with every request, including images and scripts, so large cookies slow your site down. Keep them small.

Reading cookies

On the next request, the cookie is available in $_COOKIE. Like any input, it might be missing, or contain a value you never set, so read it with a default and validate it. A preference cookie like the theme should be checked against the allowed values:

PHP Reading cookies safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The "edited cookie" contains HTML that would break out of the class attribute if it were printed directly. The whitelist check replaced it with the default before it reached the template. Even for values you can't whitelist, escape them when you print them.

PHP also changes some cookie names: dots and spaces in a name become underscores, so a cookie called user.pref shows up as $_COOKIE['user_pref']. Stick to letters, digits, - and _ in names to avoid surprises.

There's no "delete" command in HTTP. To remove a cookie, set it again with the same name, path and domain and an expiry date in the past. The browser then discards it:

PHP
<?php
setcookie('theme', '', [
    'expires' => 1,          // 1 second after 1970: long expired
    'path' => '/',           // must match the path used when setting it
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);
unset($_COOKIE['theme']);    // also forget it for the rest of this request

If the path or domain differ from the original, the browser treats it as a different cookie and the old one stays. That mismatch is the most common reason a "logout" cookie refuses to disappear.

The simulation below models a browser's cookie storage, called a cookie jar, to show expiry, path scoping and deletion working together:

PHP A simulated browser cookie jar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The cart cookie survives the deletion attempt because it was set with path=/shop and deleted with path=/. (Real browsers match paths a bit more carefully, by whole path segments, but the idea is the same.)

Security options in practice

Three options deserve a closer look, because each one blocks a specific attack:

  • secure keeps the cookie off unencrypted HTTP connections, where anyone on the same Wi-Fi could read it. On an HTTPS site there's no reason to leave it off.
  • httponly keeps JavaScript from reading the cookie. If an attacker manages to inject a script (XSS), they can't simply copy the session cookie. Use it for every cookie your JavaScript doesn't need to read.
  • samesite controls whether the cookie is attached to requests that other sites trigger, such as a form on evil.example that posts to your site. Strict never sends it cross-site (safest, but users arriving from a link appear logged out), Lax sends it only on top-level navigations with safe methods like a GET link (a good default, and what browsers assume when the option is missing), and None always sends it (needed for embedded widgets; requires secure). SameSite is an important layer against CSRF, but not a full replacement for CSRF tokens.

Cookie names starting with __Host- get extra protection from browsers: they're only accepted with secure, path=/ and no domain, so a subdomain can't overwrite them. That's an easy hardening step for session cookies.

What not to store in cookies

A cookie is stored on the user's device and sent back by the user's browser. That rules out several things:

  • Secrets and personal data: passwords, card numbers, addresses. Cookies can be read on the device, by extensions and from browser profiles.
  • Anything you trust without checking: role=admin, user_id=42, price=9.99 or discount=50. The user can change any of these in seconds.
  • Large data: shopping carts with many items or full profiles. Store those on the server (in a session or database) and keep only an ID in the cookie.

What belongs in cookies: harmless preferences (theme, language), random identifiers such as session IDs, and values protected with a signature so tampering is detected. A signature is an HMAC of the value made with a secret key only the server knows:

PHP Signed cookies detect tampering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

hash_equals() compares the signatures in constant time, so an attacker can't guess a valid signature by measuring how fast comparisons fail (Hashing, Encryption and Random Numbers explains HMACs). A signature proves the value wasn't changed, but anyone can still read it, so it's still no place for secrets. And the secret key belongs in configuration (an environment variable), never in source code as in this demo.

Cookies that aren't strictly necessary (analytics, advertising, many preference cookies) may need the user's consent under privacy laws like the EU's GDPR and ePrivacy rules. Cookies needed for the site to work, such as a session cookie or a cart, are generally exempt. Check the rules that apply to your audience.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your script calls setcookie('lang', 'fr') and on the next line reads $_COOKIE['lang']. The visitor has never been to the site. What happens?

    setcookie() only adds a Set-Cookie header to the response. The browser stores the cookie and sends it back on later requests; $_COOKIE reflects the cookies sent with the current request.
  2. 2. Which option stops JavaScript on the page from reading a cookie?

    HttpOnly hides the cookie from document.cookie, which protects it if an attacker manages to inject a script. secure controls HTTPS-only sending, and samesite controls cross-site requests.
  3. 3. A cookie was set with 'path' => '/admin'. You delete it with setcookie('token', '', ['expires' => 1, 'path' => '/']). What happens?

    Browsers identify a cookie by name, domain and path. Deleting with a different path targets a different cookie, so the /admin one survives.
  4. 4. Which of these is reasonable to store directly in a cookie?

    Users can read and edit cookies. A random identifier is fine because the real data stays on the server; passwords, permissions and prices must never be trusted from a cookie.
  5. 5. What does a signed cookie (value plus HMAC) protect against?

    Without the secret key, an edited value can't get a valid signature, so the server rejects it. The value itself is still readable, so never put secrets in it.

Summary

  • Cookies are small values the server asks the browser to store (Set-Cookie); the browser sends them back in the Cookie header, which PHP turns into $_COOKIE.
  • Set cookies with setcookie($name, $value, [...options]) before any output; a new cookie appears in $_COOKIE only on the next request.
  • Options: expires (0 = session cookie), path, domain, secure, httponly, samesite (Lax is a good default) and, since PHP 8.5, partitioned.
  • Delete a cookie by setting it again with an expiry in the past and the same path and domain.
  • $_COOKIE is untrusted input: read with a default, validate (whitelists for preferences) and escape on output.
  • Never store secrets, permissions or prices in cookies; store an ID and keep the data on the server, or sign values with hash_hmac() and check them with hash_equals().
  • Keep cookies small (about 4 KB each), and remember privacy rules for non-essential cookies.

Next: Sessions