Working with Sessions & Cookies
Prerequisites: Superglobals & handling form data
Since each request is normally independent (from How PHP Code Runs), sessions let data persist across requests for the same visitor, identified by a cookie PHP sets automatically.
session_start(); // must run before any output
$_SESSION['username'] = 'Ada';
echo $_SESSION['username']; // available on later requests too
setcookie('theme', 'dark', time() + 3600); // expires in 1 hour
echo $_COOKIE['theme'] ?? 'light';
Common mistakes
- Calling
session_start()after any HTML orechohas already been sent — this throws a "headers already sent" error, since session cookies must be set before any response body.