PHP Sessions vs Cookies: What to Use and When

Sessions and cookies both persist data across requests, but they work fundamentally differently — mixing them up leads to either security holes or broken “remember me” features.

Cookies: Client-Side Storage

// Cookies are stored in the browser and sent with every request
setcookie("theme", "dark", time() + (86400 * 30), "/");
echo $_COOKIE['theme'] ?? 'light';

Sessions: Server-Side Storage

session_start();
$_SESSION['user_id'] = 42;   // stored server-side; browser only holds a session ID cookie
echo $_SESSION['user_id'];

The Rule of Thumb

Never store sensitive data (permissions, account balances, auth state) in a cookie directly — cookies are trivially readable and editable by the client. Use sessions for anything that matters, and cookies only for non-sensitive preferences or a session identifier itself.