Sessions
Sessions Interview with follow-up questions
1. What is a session in PHP and why is it used?
A session in PHP is a server-side mechanism for maintaining state across multiple HTTP requests from the same user. Since HTTP is stateless, sessions are how web applications "remember" who a user is and what they have done.
How a session works:
session_start()generates or resumes a session. A unique session ID (a long random string) is assigned to the user.- The session ID is sent to the browser as a cookie (
PHPSESSIDby default). - Session data is stored server-side, associated with that ID.
- On subsequent requests, the browser sends the cookie; PHP loads the corresponding session data into
$_SESSION.
Common uses:
- Authentication: Storing
$_SESSION['user_id']after login to identify the authenticated user on subsequent pages. - Shopping carts: Persisting cart items between page views without requiring login.
- Wizard forms: Carrying partial form data between steps.
- Flash messages: Storing one-time messages to display after a redirect.
session_start();
$_SESSION['user_id'] = 42; // set after successful login
$_SESSION['role'] = 'admin';
Session vs. stateless authentication: Modern APIs often prefer stateless JWT (JSON Web Tokens) over sessions — the token carries the user's identity and is verified on each request without server-side storage. Understanding both approaches is important for PHP interviews in 2026.
Follow-up 1
How do you start a session in PHP?
To start a session in PHP, you need to call the session_start() function at the beginning of your script. This function initializes a new session or resumes an existing one. It also generates a unique session ID for the user and sends it as a cookie to the user's browser. Here's an example:
Follow-up 2
What is the difference between a session and a cookie in PHP?
In PHP, a session and a cookie are both used to store data, but they have some key differences:
- A session is stored on the server, while a cookie is stored on the user's browser.
- Sessions are more secure because the data is not exposed to the user, while cookies can be manipulated by the user.
- Sessions have no size limit, while cookies are limited to 4KB of data.
- Sessions are temporary and expire when the user closes the browser, while cookies can have an expiration date set.
In summary, sessions are more suitable for storing sensitive or large amounts of data, while cookies are better for storing small amounts of non-sensitive data that needs to persist across multiple sessions.
Follow-up 3
How do you destroy a session in PHP?
To destroy a session in PHP and remove all session data, you can use the session_destroy() function. This function will unset all session variables and delete the session cookie from the user's browser. Here's an example:
Follow-up 4
Can you explain how session management is handled in PHP?
In PHP, session management is handled through a combination of session handling functions and session configuration settings. Here's a brief overview of how it works:
Starting a session: You start a session by calling the
session_start()function. This initializes a new session or resumes an existing one.Storing session data: You can store data in the session by assigning values to
$_SESSIONsuperglobal array. For example,$_SESSION['username'] = 'John';.Retrieving session data: You can retrieve session data by accessing the values in the
$_SESSIONsuperglobal array. For example,$username = $_SESSION['username'];.Destroying a session: You can destroy a session and remove all session data by calling the
session_destroy()function.Session configuration: PHP provides various configuration settings related to session management, such as session lifetime, session storage location, and session cookie parameters. These settings can be modified in the
php.inifile or using theini_set()function.
It's important to note that session data is stored on the server, typically in files or a database, and is associated with a unique session ID. This session ID is usually sent to the user's browser as a cookie, allowing the server to identify the session on subsequent requests.
2. How can you set and retrieve session variables in PHP?
Session variables are stored and retrieved using the $_SESSION superglobal array. session_start() must be called before accessing $_SESSION.
Setting session variables:
Follow-up 1
What happens to session variables when a session ends?
When a session ends, either by explicitly calling session_destroy() or when it expires, all session variables associated with that session are destroyed and no longer accessible.
Follow-up 2
Can you provide an example of setting and retrieving a session variable?
Sure! Here's an example of setting and retrieving a session variable:
Follow-up 3
How can you check if a session variable is set?
To check if a session variable is set, you can use the isset() function. It returns true if the variable is set and false otherwise. For example:
3. What are some security concerns related to PHP sessions?
PHP sessions introduce several security vulnerabilities that interviewers commonly ask about:
1. Session hijacking An attacker steals a valid session ID (from a cookie, URL, network traffic, or XSS) and uses it to impersonate the victim.
Mitigations:
- Use HTTPS everywhere so cookies cannot be intercepted in transit
- Set
session.cookie_secure = 1andsession.cookie_httponly = 1 - Set
session.cookie_samesite = Strictto prevent cross-site cookie sending - Regenerate session ID periodically and after privilege changes
2. Session fixation An attacker sets a victim's session ID to a known value before the victim logs in, then uses that known ID afterward.
Mitigation:
session_start();
session_regenerate_id(true); // call immediately after successful login — destroys old session
3. Session data exposure
By default, PHP stores session data as files in /tmp or the configured session.save_path. Anyone with filesystem read access can read session contents.
Mitigations:
- Store sessions in Redis with authentication
- Restrict file permissions on the session directory
- Never store passwords or full credit card numbers in sessions
4. Cross-site request forgery (CSRF) Authenticated sessions make CSRF attacks possible — a malicious site can trigger requests that carry the victim's session cookie.
Mitigation: CSRF tokens (see form handling section) and SameSite cookie attribute.
5. Insufficient session expiry Long-lived sessions give attackers more time to exploit a stolen session ID.
Mitigation: Implement application-level timeout checking via $_SESSION['last_activity'] and call session_gc_maxlifetime appropriately.
Follow-up 1
How can you mitigate these security concerns?
To mitigate security concerns related to PHP sessions, you can:
Use secure session handling functions: PHP provides functions like
session_regenerate_id(),session_set_cookie_params(), andsession_destroy()to enhance session security.Use HTTPS: Encrypting the communication between the client and the server using HTTPS helps prevent session hijacking and eavesdropping.
Set session cookie parameters: Set the
session.cookie_httponlyparameter totrueto prevent client-side scripts from accessing the session cookie.Implement session timeout: Set an appropriate session timeout to minimize the risk of session hijacking.
Validate and sanitize session data: Always validate and sanitize session data to prevent session data tampering and XSS attacks.
Use session management best practices: Follow best practices like regenerating session IDs after successful login, destroying sessions after logout, and using strong session ID generation algorithms.
Follow-up 2
What is session hijacking and how can it be prevented?
Session hijacking, also known as session stealing or session sidejacking, is a security attack where an attacker steals a user's session ID and impersonates the user. They can then access the user's account and perform actions on their behalf.
To prevent session hijacking, you can:
Use secure session handling functions: PHP provides functions like
session_regenerate_id()to regenerate session IDs after successful login or privilege changes.Use HTTPS: Encrypting the communication between the client and the server using HTTPS helps prevent session hijacking and eavesdropping.
Set session cookie parameters: Set the
session.cookie_httponlyparameter totrueto prevent client-side scripts from accessing the session cookie.Implement session timeout: Set an appropriate session timeout to minimize the risk of session hijacking.
Monitor session activity: Implement mechanisms to detect suspicious session activity, such as multiple logins from different IP addresses or unusual session duration.
Follow-up 3
What is session fixation and how can it be prevented?
Session fixation is a security attack where an attacker sets a user's session ID to a known value before the user logs in. Once the user logs in, the attacker can use the known session ID to gain unauthorized access.
To prevent session fixation, you can:
Use secure session handling functions: PHP provides functions like
session_regenerate_id()to regenerate session IDs after successful login or privilege changes.Generate a new session ID on login: Generate a new session ID for the user upon successful login to prevent using a known session ID.
Use session cookie parameters: Set the
session.cookie_httponlyparameter totrueto prevent client-side scripts from accessing the session cookie.Implement session timeout: Set an appropriate session timeout to minimize the risk of session fixation.
Validate session ID on every request: Validate the session ID on every request to ensure it matches the one assigned to the user upon login.
4. How does PHP handle sessions on the server side?
PHP handles sessions on the server side using a configurable session save handler. The default handler stores session data as serialized files on the server's filesystem.
Default file-based flow:
session_start()is called.- PHP reads the session ID from the
PHPSESSIDcookie (or URL if session URL rewriting is enabled — avoid this for security). - PHP reads the corresponding file from
session.save_path(e.g.,/tmp/sess_abc123). - The file content is unserialized into
$_SESSION. - At the end of the request, PHP reserializes
$_SESSIONand writes it back to the file.
Key PHP session configuration:
session.save_handler = files ; or redis, memcached
session.save_path = /tmp ; where session files are stored
session.gc_maxlifetime = 1440 ; seconds before eligible for garbage collection
session.gc_probability = 1 ; GC runs on 1% of requests (1/gc_divisor)
session.gc_divisor = 100
session.use_strict_mode = 1 ; reject unrecognized session IDs
session.cookie_secure = 1 ; HTTPS only
session.cookie_httponly = 1 ; no JavaScript access
session.cookie_samesite = Lax
Custom session handlers:
PHP allows you to plug in custom session storage via session_set_save_handler(). Frameworks and Composer packages provide Redis and Memcached handlers for distributed environments where multiple web servers must share session state.
// Laravel configures this in config/session.php:
// 'driver' => env('SESSION_DRIVER', 'file') // can be: file, cookie, database, redis, etc.
Follow-up 1
Where are session files stored on the server?
By default, PHP stores session files on the server in a temporary directory specified by the 'session.save_path' configuration directive. The exact location of this directory depends on the server's configuration. However, you can change the session save path by modifying the 'session.save_path' directive in the php.ini file or by using the session_save_path() function in your PHP code.
Follow-up 2
How does PHP associate a session with a specific user?
PHP associates a session with a specific user by using a session ID. When a user visits a PHP page, PHP checks if the user has a session ID stored in a cookie. If not, PHP generates a new session ID and stores it in a cookie on the user's browser. If the user already has a session ID, PHP uses that session ID to retrieve the user's session data from the server. This allows PHP to maintain separate session data for each user.
Follow-up 3
What happens to the session data when a session ends?
When a session ends, either by calling the session_destroy() function or when the session expires, PHP removes the session data from the server. This ensures that the session data is no longer accessible to the user. However, it's important to note that the session data is not immediately deleted. PHP uses a garbage collection mechanism to periodically clean up expired session data and remove it from the server. The exact timing of this cleanup process depends on the server's configuration.
5. Can you explain the role of session IDs in PHP?
A session ID is a cryptographically random string that uniquely identifies a user's session. It is the key linking a browser to the server-side session data.
Lifecycle of a session ID:
- On first
session_start(), PHP generates a session ID using a cryptographically secure random source (configured viasession.sid_bits_per_characterandsession.sid_length— default 26 characters). - The ID is sent to the browser as the value of the
PHPSESSIDcookie. - On subsequent requests, the browser sends the cookie. PHP uses the ID to locate and load the session data.
- The ID is regenerated on privilege changes (login) to prevent session fixation.
Session ID security:
- PHP uses a CSPRNG (cryptographically secure pseudorandom number generator) for ID generation — a session ID is effectively unguessable.
session.use_strict_mode = 1rejects session IDs not generated by the server (prevents fixation where an attacker submits a known ID).session_regenerate_id(true)creates a new ID and deletes the old session file — call this on login, logout, and privilege escalation.
Session ID transmission:
- Cookie (recommended): Set
session.use_only_cookies = 1to prevent ID from being passed in URLs. - URL (avoid): Exposes session ID in logs, referrer headers, and bookmarks — a significant security risk.
session_start();
if (isLoggedIn()) {
session_regenerate_id(true); // new ID, prevents fixation
}
Follow-up 1
How are session IDs generated in PHP?
In PHP, session IDs are typically generated using a combination of random numbers and characters. The session ID generation algorithm can be configured in the PHP configuration file (php.ini) using the session.hash_function and session.hash_bits_per_character directives. By default, PHP uses the MD5 algorithm to generate session IDs.
Follow-up 2
How can you regenerate a session ID?
To regenerate a session ID in PHP, you can use the session_regenerate_id function. This function generates a new session ID and updates the session ID stored in the user's browser. It also transfers the session data to the new session ID. Regenerating the session ID is useful for preventing session fixation attacks and improving session security.
Follow-up 3
Why might you need to regenerate a session ID?
There are several reasons why you might need to regenerate a session ID in PHP:
Preventing session fixation attacks: Regenerating the session ID after a user logs in can help protect against session fixation attacks, where an attacker tries to hijack a user's session by forcing them to use a known session ID.
Improving session security: Regenerating the session ID periodically or after certain events can help improve session security by making it harder for attackers to guess valid session IDs.
Mitigating session hijacking: If you suspect that a user's session has been compromised or hijacked, regenerating the session ID can invalidate the old session and prevent further unauthorized access.
Overall, regenerating session IDs is an important security practice to protect user sessions and prevent unauthorized access to sensitive information.
Live mock interview
Mock interview: Sessions
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.