How do PHP sessions work?
Call session_start() before any output, then read and write $_SESSION like an array. PHP stores the data server-side and gives the browser only an ID in a cookie.
session_start();
$_SESSION['user_id'] = 42;
$_SESSION['name'] = 'Dom';
// on any later page
session_start();
echo $_SESSION['name'] ?? 'guest';#What is actually happening
session_start()looks for a session cookie (default namePHPSESSID).- If there is none, PHP generates an ID and sends it as a cookie.
- The data lives in a file on the server, keyed by that ID.
The browser never sees the contents — only the ID. That is what makes sessions suitable for things a cookie should not hold.
#session_start() must come before output
It sends a cookie header, so the same "headers already sent" rule applies. Put it at the very top of the file.
#Logging in and out
// On successful login — regenerate to prevent session fixation
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
// Logging out
$_SESSION = [];
session_destroy();session_regenerate_id(true) is the line people omit. Without it, an attacker who can set a victim's session ID before login retains a valid session afterwards.
#Harden the cookie
In php.ini or before session_start():
session_set_cookie_params([
'httponly' => true, // JavaScript cannot read it
'secure' => true, // HTTPS only
'samesite' => 'Lax', // blocks most CSRF
]);#Sessions are not a database
$_SESSION is loaded and written on every request. Keep it to identifiers and small flags — a user ID, a cart ID, a CSRF token. Look the rest up when you need it.