Sessions persist data across multiple requests for the same visitor, stored server-side and linked to the browser via a session ID cookie:
session_start(); // must be called before any output
$_SESSION['user_id'] = 42;
$_SESSION['username'] = 'alice';
echo $_SESSION['username']; // available on later requests, same visitor
unset($_SESSION['user_id']); // remove one value
session_destroy(); // end the session entirely (e.g. on logout)
Cookies are small pieces of data stored in the browser itself and sent with every request:
setcookie('theme', 'dark', time() + 86400 * 30, '/', '', true, true); // 30 days, secure, httponly
echo $_COOKIE['theme'] ?? 'light';
Essential security practices:
- XSS prevention: always escape output with
htmlspecialchars($value, ENT_QUOTES, 'UTF-8')before printing user-supplied data into HTML. - CSRF protection: include a random, unpredictable token in every form and verify it on submission, so requests can't be forged from another site.
- SQL injection prevention: never concatenate user input into SQL — always use prepared statements (covered in the Databases chapter).
- Password storage: never store plain-text passwords — use
password_hash($password, PASSWORD_DEFAULT)to hash andpassword_verify($password, $hash)to check. - Cookie flags: set
httponly(blocks JavaScript access) andsecure(HTTPS only) on sensitive cookies like session IDs.