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 is a small piece of data stored directly in the user's browser and sent with every request to the same domain. A PHP session stores data on the server, identified by a session ID that's typically transmitted to the browser as a single cookie (PHPSESSID by default).

Common causes

  • Cookies are limited in size (about 4KB) and are visible/editable by the client, making them unsuitable for sensitive or large data
  • Sessions solve this by keeping the actual data server-side, with only an opaque identifier exposed to the client

How to fix it

  • Use session_start() at the top of any script that needs to read or write $_SESSION data
  • Use cookies directly (setcookie()) only for non-sensitive preferences that should persist without a server round-trip, like a 'remember my theme' setting
  • Never store sensitive data (passwords, auth tokens) directly in a cookie — keep it in the session and rely on the session ID cookie being HttpOnly and Secure

Example

session_start();
$_SESSION['user_id'] = 42;

// later request
session_start();
echo $_SESSION['user_id']; // 42

FAQ

Does PHP delete session data automatically?

Sessions expire based on garbage collection settings (session.gc_maxlifetime) and are typically cleaned up by PHP periodically, not instantly the moment they expire.

More PHP articles