A cookie is a small piece of text that a website asks the browser to store. The browser then sends it back with every request to the same site.
The server sets a cookie with an HTTP header:
Set-Cookie: theme=dark; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=Lax
On later requests, the browser sends:
Cookie: theme=dark
PHP reads it into $_COOKIE.
What cookies are for
- Preferences: language, theme, “dismiss this banner”.
- The session ID: the cookie
PHPSESSIDis how sessions work. - Remember me tokens (carefully, see Remember Me).
- Analytics and ads, when the visitor agrees.
Limits
- About 4 KB per cookie, and a limited number per site.
- Sent with every request to your site, including images. Big cookies slow everything down.
- The visitor can see, edit and delete cookies.
What to put in a cookie
Small, harmless values: theme=dark, lang=en.
What never to put in a cookie
- Passwords or tokens that grant access without being random and unguessable.
- A
logged_in=1flag orrole=admin. A visitor can change the text. - Personal data.
If a value must be trusted, keep it in a session on the server, and put only a random ID in the cookie.
Cookie attributes
| Attribute | What it does |
|---|---|
expires / max-age | When the cookie dies. Without one, it ends when the browser closes (a session cookie) |
path | The part of the site that receives it (/ is everything) |
domain | Which host receives it |
secure | Send only over HTTPS |
httponly | JavaScript cannot read it. Protects against theft through XSS |
samesite | Controls whether it is sent with cross-site requests (Lax or Strict) |
Cookies and privacy law
Rules such as the GDPR and similar laws in other places can require consent for cookies that are not strictly necessary (analytics, advertising). Cookies that are strictly necessary, such as the session cookie for a login, are generally allowed without a banner. Ask a legal adviser for the rules that apply to your site.
See your own cookies
Open the browser developer tools (F12) and look at Application (Chrome, Edge) or Storage (Firefox), then Cookies. You can see every cookie, its value and its attributes.