Sessions and Cookies
Sessions and Cookies
HTTP is stateless, so each request is independent. Cookies and sessions give your app a way to remember users between requests.
Cookies
A cookie is a small value the browser stores and sends back with every request:
setcookie('theme', 'dark', time() + 3600);
// later, on the next request:
echo $_COOKIE['theme'];
Cookies are readable on the client and limited in size, so store only small, non-sensitive data there.
Session basics
Sessions keep data on the server and send the client only a session id cookie:
session_start();
$_SESSION['user_id'] = 42;
// every page can now read $_SESSION
Call session_start before any output. The id cookie ties the browser to the server-side data.
Reading and destroying
if (isset($_SESSION['user_id'])) { ... }
session_unset();
session_destroy();
Logout flows clear the session and empty the cookie side so nothing lingers.
Security notes
Set HttpOnly so JavaScript cannot read the session cookie, use Secure and SameSite flags over HTTPS, and regenerate the session id after login to prevent fixation. Sessions store sensitive data server-side, which is why they fit authentication and carts.
Key Points
- Cookies live on the client and resend on each request.
- Sessions store data on the server behind an id cookie.
- Call session_start before any output.
- Destroy sessions at logout.
- Use HttpOnly and SameSite flags for safer cookies.