Skip to content
Happy Programming Guide
Start learning
Web Development

Sessions, Cookies and Security

How the web remembers who you are: cookies, sessions, tokens, the attributes that protect them, and the attacks each one prevents.

A row of padlocks on a fence

HTTP has no memory. Every request arrives as if it were the first, which is why a website needs some way to recognise you between clicks. That mechanism is almost always a cookie, and the details of how it is set determine whether your users’ accounts are safe. This guide explains the model and the attacks, without tying it to one language.

The problem#

You sign in. You click a link. The server receives a completely fresh request with no memory of the first one. Something has to travel with every request to say “this is the same person”.

A cookie is that something. The server sends one, the browser stores it, and the browser attaches it to every subsequent request to that site automatically.

Output
Server -> Browser
Set-Cookie: session=8f4a9c2e1b...; HttpOnly; Secure; SameSite=Lax; Path=/

Browser -> Server, on every later request
Cookie: session=8f4a9c2e1b...

Sessions or tokens#

Two ways to use that cookie value.

Server-side sessions. The cookie holds a meaningless random identifier. The real data lives on the server, keyed by that identifier.

Output
Cookie:  session=8f4a9c2e1b...
Server:  8f4a9c2e1b... -> { userId: 42, role: "editor", expires: ... }

Tokens. The cookie holds signed data. The server verifies the signature and reads the contents; it stores nothing.

Output
Cookie:  token=eyJhbGciOi...  (contains userId and role, signed)
Server session Signed token
Server storage required none
Revoke immediately easy hard
Scales across servers needs shared storage naturally
Size sent per request tiny larger
Data can go stale no yes, until it expires

The revocation difference is the one that matters most. With sessions, deleting the record signs someone out instantly. With tokens, a stolen token stays valid until it expires, unless you add a deny-list — which reintroduces the server storage you were avoiding.

The four attributes#

Output
Set-Cookie: session=abc; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=28800
  • HttpOnly — JavaScript cannot read it. This is what stops a cross-site scripting flaw from stealing the session outright, and it is why storing a session token in localStorage is a step backwards.
  • Secure — only sent over HTTPS, so it cannot be captured on an open network.
  • SameSite — controls whether the cookie is sent on requests originating from other sites. Lax is a sensible default; Strict is safer and means a link from an email arrives logged out; None requires Secure and should be rare.
  • Max-Age or Expires — without one, the cookie disappears when the browser closes. That is right for a session cookie and wrong for “remember me”.

Session hijacking#

If an attacker obtains the session identifier, they are you. Nothing else is needed — no password, no second factor.

The defences follow directly from how it can be obtained:

  • Intercepted on the network — use HTTPS everywhere and the Secure flag.
  • Read by injected JavaScript — HttpOnly, plus fixing the XSS itself.
  • Guessed — generate identifiers from a cryptographically secure random source, never a timestamp or a counter.
  • Left lying around — expire sessions, and delete them on logout.
Output
// Bad - predictable
session_id = timestamp + user_id

// Good - 128 bits or more of secure randomness
session_id = secure_random(32).hex()

Session fixation#

A subtler attack. Instead of stealing your session identifier, the attacker gives you one they already know — through a crafted link, or by setting it from a shared subdomain — and waits for you to log in with it.

The fix is one line, and it is the single most important thing on this page:

Output
on successful login:
    regenerate the session identifier
    then store the user id

Every framework has a method for this. Because the identifier changes at the moment privileges are granted, the one the attacker planted is never associated with a logged-in user.

Cross-site request forgery#

Because cookies are attached automatically, any other site can make your browser send an authenticated request:

HTML
<!-- On an attacker's page, while you are logged in elsewhere -->
<form action="https://yourbank.example/transfer" method="post">
  <input type="hidden" name="to" value="attacker">
  <input type="hidden" name="amount" value="1000">
</form>
<script>document.forms[0].submit();</script>

Two defences, used together:

  1. SameSite=Lax or Strict on the session cookie, which stops it being sent on most cross-site requests.
  2. A CSRF token — a random value tied to the session, included in every form and checked on submission. The attacker’s page cannot read it, so it cannot include it.
HTML
<form method="post" action="/transfer">
  <input type="hidden" name="csrf" value="RANDOM_VALUE_FROM_SESSION">
</form>

Compare the token in constant time, and only require it for requests that change something — a GET request should never have side effects in the first place.

What to do at each point#

Event Action
Login succeeds regenerate the identifier, then store the user id
Privileges change regenerate again
Logout delete the server-side record and clear the cookie
Password changed invalidate every other session for that user
Inactivity expire after a sensible period
Absolute age force a fresh login eventually, however active

Clearing the cookie on logout is not enough on its own — if the server-side record survives, anyone who captured the identifier earlier can still use it.

Remember me#

A long-lived login should not be a long-lived session. The usual pattern is a separate token:

Output
Store:  user_id, selector, hashed_validator, expires_at
Cookie: selector:validator

On arrival with no session:
  look up by selector
  compare the hash of the validator in constant time
  if it matches: start a new session, and issue a NEW remember token

Storing a hash rather than the raw validator means a database leak does not hand out working logins. Rotating the token on each use means a stolen one is detectable — if the old value is presented again, something is wrong.

Cookies for other purposes#

Not every cookie is a session. Preferences, a theme choice, a dismissed banner — these can go in an ordinary cookie or in browser storage, and they do not need HttpOnly because nothing depends on them being secret.

Keep them small. Cookies are sent on every single request to your domain, including for images and stylesheets, so a large cookie is a permanent tax on page speed.

Questions people ask#

Where should a session token be stored on the client?

In an HttpOnly cookie set by the server. Anything readable by JavaScript — localStorage, sessionStorage, an ordinary cookie — is readable by an injected script.

Do I need a cookie banner?

It depends on what the cookie does and where your users are. Strictly necessary cookies, such as a login session, are generally treated differently from tracking. Take proper advice for anything commercial — the technology is not what decides it.

How long should a session last?

Short enough that an abandoned session on a shared computer is not a problem, long enough that people are not signed out mid-task. A few hours of inactivity is common; anything handling money should be shorter.

Is a JWT more secure than a session?

No — it is a different trade-off. Tokens remove server storage and make immediate revocation hard. Sessions require storage and make revocation trivial. Choose on your requirements, not on which sounds more modern.

Where to go next#

Sessions and cookies in PHP, with working codeRead next

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *