7 questions foundWhat is a session in PHP, and how does it let a web application remember information about a user across multiple separate page requests?
Beginner A session lets a web application store data related to a specific visitor on the server side and retrieve that same data on later requests from the same visitor, and since HTTP itself is stateless, meaning each request is normally treated independently with no memory of previous requests, PHP achieves this continuity by assigning the visitor a unique session identifier, usually stored in a cookie in their browser, which is then sent back with every subsequent request so the server can look up the correct stored session data.
session_start();
$_SESSION['user_id'] = 42;
// On a later page
echo $_SESSION['user_id'];
Real-world example An online store uses a session to remember which items a shopper has added to their cart as they browse different product pages, without needing the shopper to log in or resend that cart information with every single request.
Common follow-ups: Where is session data actually stored by default on the server?;What happens to session data if a user closes their browser?
Security;Basics & Types
What is a cookie, and how does it differ from a session in terms of where the actual data is stored?
Beginner A cookie is a small piece of data that the server asks the visitor's browser to store and send back with future requests to the same website, and unlike a session, where the actual data lives on the server and only a small identifier is stored in the browser, a cookie can hold the actual data itself directly within the browser, though cookies are more limited in size and should never be used to store sensitive information since they are fully visible and editable by the person using the browser.
setcookie('theme_preference', 'dark', time() + (86400 * 30), '/');
echo $_COOKIE['theme_preference'] ?? 'light';
Real-world example A website remembers a visitor's preferred light or dark theme setting by storing that choice directly in a cookie, so the same preference is automatically applied the next time that visitor returns, even without needing to log in.
Common follow-ups: How long can a cookie realistically persist on a user's device?;Why should sensitive data never be stored directly inside a cookie?
Security;Form Handling & Validation
What are the httponly and secure flags on a cookie, and why are they important for protecting session cookies specifically?
Intermediate The httponly flag on a cookie tells the browser to prevent that cookie from being accessed through client side JavaScript, which significantly reduces the risk that a cross site scripting attack could steal the cookie's value, while the secure flag ensures the cookie is only ever sent over an encrypted HTTPS connection and never over plain unencrypted HTTP, and since the session cookie holding a visitor's session identifier is essentially the key to their entire authenticated session, protecting it with both of these flags is considered an essential security practice.
session_set_cookie_params([
'httponly' => true,
'secure' => true,
'samesite' => 'Lax',
]);
session_start();
Real-world example A banking application configures its session cookie with both the httponly and secure flags enabled, ensuring the session identifier cannot be read by injected malicious JavaScript and is never accidentally transmitted over an insecure connection.
Common follow-ups: What does the samesite cookie attribute do, and what are its possible values?;Can these protective flags be applied to cookies other than the session cookie?
Security;Form Handling & Validation
How does PHP's session garbage collection work, and what settings control how long session data is kept before it is considered expired and eligible for cleanup?
Intermediate PHP periodically runs a garbage collection process that removes session data files that have not been accessed within a configured maximum lifetime, controlled by the session.gc_maxlifetime setting, and since this cleanup process runs probabilistically based on session.gc_probability and session.gc_divisor rather than on every single request, on a low traffic site it is possible for expired session files to sit unused for longer than expected before they are actually cleaned up, which is worth considering when session storage space or expiration timing genuinely matters.
ini_set('session.gc_maxlifetime', 1800);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);
Real-world example An application configures its session lifetime to thirty minutes of inactivity, automatically expiring a shopper's session and requiring them to log in again if they leave their browser open and inactive for longer than that configured window.
Common follow-ups: How can you manually force expired sessions to be cleaned up immediately rather than waiting for the probabilistic garbage collection?;What are the tradeoffs of storing session data in a database instead of the default file based storage?
PDO & Databases;Performance Optimization & OPcache
What is session fixation, and how does regenerating the session identifier after a successful login help prevent this attack?
Intermediate Session fixation is an attack where an attacker tricks a victim into using a session identifier that the attacker already knows, then waits for the victim to log in, at which point the attacker can use that same known session identifier to access the now authenticated session as if they were the victim, and calling session_regenerate_id immediately after a successful login generates a brand new session identifier for the now authenticated user, invalidating whatever identifier existed beforehand and making it useless to an attacker even if they had somehow set it in advance.
if (password_verify($inputPassword, $storedHash)) {
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
}
Real-world example A login system regenerates the session identifier immediately after verifying a user's password is correct, ensuring that any session identifier an attacker may have previously fixed onto the victim's browser becomes worthless once the victim actually logs in.
Common follow-ups: What does passing true to session_regenerate_id actually do differently compared to passing no argument?;At what other points in an application might it also be wise to regenerate the session identifier?
Security;Basics & Types
How can you store session data in a shared storage system like Redis or a database instead of the default local file storage, and why is this often necessary for applications running on multiple servers?
Advanced PHP's default session storage saves session data as individual files on the local server's file system, which works fine for a single server, but becomes a significant problem for an application running behind a load balancer across multiple servers, since a user's session file might be saved on one server but their next request could be routed to a completely different server that has no access to that file, and implementing a custom session handler backed by shared storage like Redis or a database, accessible equally from every server, solves this by centralizing where session data actually lives.
session_set_save_handler(new RedisSessionHandler($redisClient));
session_start();
Real-world example A popular web application running across ten different load balanced servers stores all session data in a centralized Redis instance, ensuring a user's session remains valid and consistent no matter which specific server happens to handle each of their individual requests.
Common follow-ups: What interface must a custom PHP session handler implement?;How does using Redis for session storage compare to using a shared database table for the same purpose?
Redis Caching Strategies in PHP;Deployment & Hosting for PHP Applications
What are the security and architectural considerations of using stateless, token based authentication such as JWT instead of traditional server side sessions for an API?
Advanced Traditional server side sessions require the server to maintain some form of state about each authenticated user, which can complicate scaling an application across multiple servers without shared session storage, whereas a stateless token like a JWT contains all the necessary claims about the user directly within the token itself, cryptographically signed so the server can verify it has not been tampered with, without needing to look anything up in shared storage at all, though this approach introduces its own considerations, such as how to properly revoke a token before its natural expiration if a user's account is compromised.
$token = JWT::encode(['user_id' => 42, 'exp' => time() + 3600], $secretKey, 'HS256');
Real-world example A mobile app backend API issues a signed JWT to a user after login, letting any of several independent API servers verify the token's authenticity and identify the user directly from the token itself, without needing to check a shared session store on every single request.
Common follow-ups: How can you revoke a JWT before its expiration time is reached if necessary?;What is the tradeoff between a shorter lived access token and a longer lived refresh token?
Security;RESTful API Development with PHP