Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Web and Security

PHP setcookie() function

Reference for PHP setcookie(): create, read and delete cookies, set expires, path, secure, httponly and samesite with the options array, and fix 'headers already sent'.

setcookie() asks the browser to store a small piece of data and send it back with every later request to your site. PHP puts the cookie into the response as a Set-Cookie header, so, like header(), it must be called before any output.

The cookie is not available in $_COOKIE during the request that sets it. The browser sends it back on the next request, and only then does PHP fill $_COOKIE. Use the options-array form (PHP 7.3 and later) to set security flags clearly.

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

Try it

Cookies belong to browsers, and the editor runs PHP from the command line, so no Set-Cookie header reaches anyone. The examples show the return values, the "too late" warning and how $_COOKIE is read, by filling it by hand the way PHP does from the request's Cookie header. The header-building helper is an illustration, not PHP's own code.

PHP Return values and the 'headers already sent' warning

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.

PHP Reading cookies and building a Set-Cookie line

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.

Syntax

PHP
setcookie(
    string $name,
    string $value = "",
    int $expires_or_options = 0,
    string $path = "",
    string $domain = "",
    bool $secure = false,
    bool $httponly = false
): bool

setcookie(string $name, string $value = "", array $options = []): bool
Name Description
$name The cookie name.
$value The value; it is URL-encoded automatically and decoded again into $_COOKIE. An empty string tells PHP to send an expiring cookie, which deletes it.
expires Unix timestamp when the cookie expires. 0 makes a session cookie that lives until the browser closes. Past timestamps delete the cookie.
path URL path the cookie applies to. Use '/' for the whole site.
domain Host the cookie applies to; leave empty for the current host only.
secure If true, send only over HTTPS.
httponly If true, JavaScript cannot read it (document.cookie).
samesite 'Lax', 'Strict' or 'None' (which requires secure). Limits cross-site sending.

The options array accepts the keys expires, path, domain, secure, httponly and samesite.

Return value: true if the header was queued, false if headers were already sent. A true does not mean the browser accepted the cookie.

Errors / Exceptions: a warning when headers were already sent; ValueError for a name with illegal characters (for example =, ; or a space) and for an unknown key in the options array.

Usage notes

  • Next request only. To use a value immediately, set $_COOKIE['x'] = ... yourself as well.
  • Always set path (usually '/'). Without it the cookie applies only to the current directory, a common cause of "my cookie disappeared".
  • Security flags: httponly for anything JavaScript does not need, secure for HTTPS sites, samesite Lax by default.
  • Deleting: send the same name, path and domain with an expiry in the past, and unset $_COOKIE[name].
  • Do not trust cookie values. The visitor can edit them. Validate against a whitelist, and never store roles, prices or passwords there; use a session with an ID instead.
  • Size and count limits: about 4 KB per cookie and a few dozen per site. Store an ID and keep the data on the server.
  • Cookie prefixes: names starting __Host- or __Secure- make browsers enforce secure and a root path.
  • setrawcookie() sends the value without URL-encoding. Rarely needed.
  • Expiry in seconds: write time() + 3600 for one hour; long lifetimes need consent in many regions.