Cookies

Cookies are small text files that the server asks the browser to store and send back with every subsequent request to that domain. They're transmitted via HTTP headers, not as part of the HTML body, which is why setcookie() must be called before any output (before , echo, or even whitespace).

Key concepts:

  • Creating a cookie: Use setcookie(name, value, expire, path, domain, secure, httponly). Only name is required; all other parameters are optional.
  • Modifying a cookie: Call setcookie() again with the same name but different values. There's no separate “update” function – you're just overwriting it.
  • Deleting a cookie: Call setcookie() with the same name and an expiration time in the past (e.g., time() – 3600). The empty value is optional but conventional.
  • Reading cookies: Use the $_COOKIE superglobal. Important: $_COOKIE only reflects what the browser sent with the current request, not what you just set in the same script execution. To see a newly-set cookie, you need to refresh the page.
  • Common parameters:
  • expire: Unix timestamp (use time() + seconds)
  • path: / makes it available site-wide
  • httponly: true prevents JavaScript access (security best practice)

Typical flow: Set cookie → browser stores it → browser sends it back on next request → you read it from $_COOKIE.