Skip to content

PHP Tutorial Sessions and Cookies

What Are Cookies?

Lesson 180 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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:

Text
PLAIN
Set-Cookie: theme=dark; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=Lax

On later requests, the browser sends:

Text
PLAIN
Cookie: theme=dark

PHP reads it into $_COOKIE.

What cookies are for

  • Preferences: language, theme, “dismiss this banner”.
  • The session ID: the cookie PHPSESSID is 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.

Small, harmless values: theme=dark, lang=en.

  • Passwords or tokens that grant access without being random and unguessable.
  • A logged_in=1 flag or role=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.

AttributeWhat it does
expires / max-ageWhen the cookie dies. Without one, it ends when the browser closes (a session cookie)
pathThe part of the site that receives it (/ is everything)
domainWhich host receives it
secureSend only over HTTPS
httponlyJavaScript cannot read it. Protects against theft through XSS
samesiteControls 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.

info
Cookies are just text
A cookie is not private, not secure and not permanent. Everything that must be protected stays on the server.