HTTP is stateless; sessions and cookies let PHP recognize returning users—shopping carts, login state, preferences.
Cookies
Small name/value pairs the server sends via Set-Cookie. Client sends them back on each request. Set with setcookie before output:
setcookie('theme', 'dark', [
'expires' => time() + 86400 * 30,
'path' => '/',
'httponly' => true,
'samesite' => 'Lax',
'secure' => true, // HTTPS only
]);
Sessions
session_start();
$_SESSION['user_id'] = 42;
$userId = $_SESSION['user_id'] ?? null;
PHP stores session data server-side (files, Redis, database) and issues a session ID cookie—prefer sessions for sensitive auth state over large client cookies.
Playground note
Session functions may not persist between runner invocations. Study the API; test login flows on a local Apache/Nginx + PHP stack.
Important interview questions and answers
- Q: Session vs cookie?
A: Cookies live on the client (size limits, visible); sessions store data server-side with only an ID cookie on the client. - Q: HttpOnly and Secure flags?
A: HttpOnly blocks JavaScript access (mitigates XSS cookie theft); Secure sends cookie only over HTTPS.
Self-check
- Why call
session_start()before reading$_SESSION? - What SameSite=Lax helps prevent?
Pitfall: Never store passwords in cookies—use server sessions for auth state and HttpOnly + Secure flags.
Interview prep
- Session vs cookie storage?
Sessions store data server-side with an ID cookie on the client; plain cookies store data on the client—limited size and visible to JS unless HttpOnly.