PHP Sessions vs Cookies — What's the Difference?
Cookies store small data on the client browser; sessions store data server-side and use a cookie only to reference it. Learn when to use each in PHP.
Published September 18, 2026
A cookie stores data in the visitor's browser; a session stores data on the server and gives the browser only an ID cookie to find it. Keep sensitive data in sessions and small preferences in cookies.
The concept
Cookies are sent with every request, can be read and edited by the user, and are limited to about 4 KB. Anything stored there must be treated as untrusted.
A session keeps the real data in server storage (files by default) keyed by a random ID such as PHPSESSID. The browser holds only that ID, so users cannot tamper with the data itself.
How a session login works
Practical examples
Using a session
session_start();
$_SESSION['user_id'] = 7;
// later request
session_start();
echo $_SESSION['user_id']; // 7Setting a cookie safely
setcookie('theme', 'dark', [
'expires' => time() + 86400 * 30,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);Logging out
session_start();
$_SESSION = [];
session_destroy();Common mistakes
- Storing passwords or roles in a cookie the user can edit.
- Forgetting session_start() before using $_SESSION.
- Not calling session_regenerate_id(true) after login (session fixation).
- Setting cookies without Secure and HttpOnly flags.
Key takeaways
- Cookie = client storage, session = server storage plus an ID cookie.
- Never trust cookie contents.
- Regenerate the session ID on login.
FAQ
Do sessions need cookies?
Normally yes for the session ID, though it can be passed in the URL (not recommended).
How long does a session last?
Until it expires on the server (session.gc_maxlifetime) or the browser drops the ID cookie.