PHP Sessions and Cookies
PHP Sessions and Cookies Interview with follow-up questions
1. What are PHP Sessions and how do they work?
A PHP session is a server-side mechanism for persisting user-specific data across multiple HTTP requests. Because HTTP is stateless, sessions provide the statefulness web applications need.
How sessions work:
- A user makes their first request.
session_start()generates a unique session ID (a long random string, e.g.,abc123xyz...). - PHP stores the session ID in a cookie named
PHPSESSID(by default) on the client's browser. - Session data is stored server-side — by default in files in the
session.save_pathdirectory. - On subsequent requests, the browser sends the
PHPSESSIDcookie. PHP reads the ID, finds the corresponding session file, loads the data into$_SESSION. - When
session_destroy()is called (e.g., on logout), the session data is deleted.
session_start(); // must be called before any output
$_SESSION['user_id'] = 42; // store data
$_SESSION['role'] = 'admin';
// On a later page:
session_start();
echo $_SESSION['user_id']; // 42
// On logout:
session_unset(); // clear $_SESSION array
session_destroy(); // delete server-side session data
Session storage alternatives (important for production/scaling):
- Files (default) — not suitable for multi-server deployments
- Redis or Memcached — shared, fast; used in load-balanced environments
- Database — durable, queryable session storage
Configure via session.handler or call session_set_save_handler().
Follow-up 1
How can you start a PHP session?
To start a PHP session, you need to call the session_start() function at the beginning of your PHP script. This function will either create a new session or resume an existing session based on the session ID provided by the user's browser or passed through the URL. Here's an example:
Follow-up 2
What is the role of the session_start() function in PHP?
The session_start() function in PHP is used to start a new session or resume an existing session. It initializes the session data and assigns a unique session ID to the user. This function must be called before any session variables are accessed or modified. If the session has already been started, calling session_start() again will resume the existing session.
Follow-up 3
How can you destroy a PHP session?
To destroy a PHP session 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:
2. What are PHP Cookies and how do they differ from sessions?
Cookies are small key-value pairs stored in the client's browser. The browser sends them back with every subsequent request to the same domain. Cookies persist across browser sessions (if given an expiry) and can be read and deleted by both server and (unless HttpOnly) client-side JavaScript.
Sessions store data on the server. Only a session ID is sent to the client (as a cookie named PHPSESSID by default). The actual session data never leaves the server.
Comparison:
| Feature | Cookie | Session |
|---|---|---|
| Storage location | Client browser | Server |
| Capacity | ~4 KB per cookie | Limited only by server storage |
| Security | Visible on client; can be tampered with | Data stays server-side; only ID sent to client |
| Lifespan | Set by expires parameter |
Ends when browser closes (or session.gc_maxlifetime) |
| Accessibility | $_COOKIE |
$_SESSION |
When to use cookies:
- Remembering preferences (theme, language) across browser sessions
- "Remember me" tokens (store a secure, randomized token; map it to a user in the DB)
- Analytics tracking IDs
When to use sessions:
- Authenticated user state (user ID, roles)
- Shopping cart contents during a session
- Form wizard data between steps
Security best practice: Never store sensitive data (passwords, credit card numbers) in cookies. Cookies should only contain opaque identifiers; the sensitive data stays server-side.
Follow-up 1
How can you set a cookie in PHP?
To set a cookie in PHP, you can use the setcookie() function. The setcookie() function takes multiple parameters, including the name of the cookie, the value of the cookie, and optional parameters such as the expiration time, path, and domain.
Here's an example of how to set a cookie in PHP:
In this example, a cookie named 'username' is set with the value 'John Doe'. The cookie will expire in 1 hour (3600 seconds) and will be accessible from the root directory of the website.
Follow-up 2
How can you retrieve a cookie value in PHP?
To retrieve a cookie value in PHP, you can use the $_COOKIE superglobal variable. The $_COOKIE variable is an associative array that contains all the cookies sent by the client's browser.
Here's an example of how to retrieve a cookie value in PHP:
In this example, the value of the 'username' cookie is retrieved from the $_COOKIE variable. If the cookie exists, the username is displayed. Otherwise, a message indicating that no cookie was found is displayed.
Follow-up 3
What is the role of the setcookie() function in PHP?
The setcookie() function in PHP is used to set a cookie. It takes multiple parameters, including the name of the cookie, the value of the cookie, and optional parameters such as the expiration time, path, and domain.
The setcookie() function sends a Set-Cookie header to the client's browser, instructing it to store the cookie. The cookie will then be sent back to the server with subsequent requests.
Here's an example of how to use the setcookie() function:
In this example, a cookie named 'username' is set with the value 'John Doe'. The cookie will expire in 1 hour (3600 seconds) and will be accessible from the root directory of the website.
3. How can you handle session timeout in PHP?
Session timeout is the process of invalidating a session after a period of inactivity, protecting users from session hijacking if they leave a browser unattended.
PHP's built-in session garbage collection:
session.gc_maxlifetime (default: 1440 seconds / 24 minutes) sets how long session data can sit on the server before being eligible for garbage collection. However, garbage collection is probabilistic — not an exact timeout.
Reliable application-level timeout: Store a last-activity timestamp in the session and check it on each request:
session_start();
$timeout = 1800; // 30 minutes
if (isset($_SESSION['last_activity']) &&
(time() - $_SESSION['last_activity']) > $timeout) {
// Session expired
session_unset();
session_destroy();
header('Location: /login?reason=timeout');
exit;
}
$_SESSION['last_activity'] = time(); // update on every request
Additional best practices:
- Regenerate the session ID on login to prevent session fixation:
session_regenerate_id(true) - Set the session cookie
expiresso the browser discards it when closed (omitexpiresinsetcookie/session_set_cookie_paramsfor a session cookie) - Set
session.gc_maxlifetimeinphp.inito match your application's timeout value
Scaling note: If using file-based sessions on multiple servers, the session file must be on shared storage (NFS, Redis, Memcached) so all servers can read it. Redis is the most common production choice.
Follow-up 1
What is the default session timeout in PHP?
The default session timeout in PHP is 1440 seconds (24 minutes). This means that if a user is inactive for more than 24 minutes, their session will expire and they will need to log in again.
Follow-up 2
How can you change the session timeout in PHP?
To change the session timeout in PHP, you can modify the session.gc_maxlifetime configuration directive in your PHP configuration file (php.ini) or in your PHP script using the ini_set() function. For example, to set the session timeout to 30 minutes, you can use the following code:
ini_set('session.gc_maxlifetime', 1800);
Follow-up 3
What happens when a PHP session times out?
When a PHP session times out, the session data is destroyed and the user will need to log in again. Any unsaved data in the session will be lost. It is important to handle session timeouts gracefully in your application to provide a good user experience. You can redirect the user to a login page or display a message indicating that their session has expired.
4. What is the role of $_SESSION and $_COOKIE superglobals in PHP?
Both $_SESSION and $_COOKIE are superglobal arrays that store persistent data across requests, but they store data in different locations.
$_SESSION
- Stores data on the server, keyed by session ID
- Data is available within a single user's session across multiple page requests
- Requires
session_start()to be called before use - Data is lost when the session expires or is destroyed
session_start();
$_SESSION['cart_count'] = 5; // store
echo $_SESSION['cart_count']; // read
unset($_SESSION['cart_count']); // remove one key
session_destroy(); // destroy entire session
$_COOKIE
- Contains cookies sent by the browser in the current request
- Read-only within the current request — set new cookies with
setcookie() - Cookies are stored in the browser and sent with every request to the domain
// Reading a cookie
$theme = $_COOKIE['theme'] ?? 'light';
// Setting a cookie (must be before any output)
setcookie('theme', 'dark', [
'expires' => time() + 86400 * 365,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
Key distinction: $_COOKIE reflects cookies the browser sent; to set a new cookie you use setcookie(), and the new value won't appear in $_COOKIE until the next request.
Follow-up 1
How can you store data in the $_SESSION superglobal?
To store data in the $_SESSION superglobal, you can use the session_start() function to start or resume a session, and then assign values to specific keys in the $_SESSION array. For example:
session_start();
$_SESSION['username'] = 'John';
$_SESSION['email'] = '[email protected]';
Follow-up 2
How can you retrieve data from the $_COOKIE superglobal?
To retrieve data from the $_COOKIE superglobal, you can simply access the value of a specific cookie by using its name as the key in the $_COOKIE array. For example:
$username = $_COOKIE['username'];
$email = $_COOKIE['email'];
Follow-up 3
What is the difference between $_SESSION and $_COOKIE?
The main difference between $_SESSION and $_COOKIE is where the data is stored:
$_SESSION stores data on the server side, associated with a specific user session. This makes it more secure as the data is not exposed to the client.
$_COOKIE stores data on the client side as a cookie. This makes it less secure as the data can be accessed and modified by the client.
Additionally, $_SESSION is typically used for storing sensitive or important data, while $_COOKIE is often used for storing non-sensitive data or user preferences.
5. How can you handle session and cookie security in PHP?
Securing sessions and cookies requires multiple layers of defense:
Session security:
// 1. Configure secure session settings (php.ini or at runtime)
ini_set('session.cookie_secure', '1'); // HTTPS only
ini_set('session.cookie_httponly', '1'); // no JavaScript access
ini_set('session.cookie_samesite', 'Lax'); // CSRF protection
ini_set('session.use_strict_mode', '1'); // reject unrecognized session IDs
// 2. Start session and regenerate ID on privilege change
session_start();
session_regenerate_id(true); // call on login to prevent session fixation
// 3. Implement an application-level timeout
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > 1800) {
session_unset();
session_destroy();
header('Location: /login');
exit;
}
$_SESSION['last_activity'] = time();
// 4. Destroy session completely on logout
session_unset();
session_destroy();
setcookie(session_name(), '', time() - 3600, '/', '', true, true); // expire the cookie
Cookie security:
setcookie('token', $value, [
'expires' => time() + 86400,
'path' => '/',
'secure' => true, // HTTPS only
'httponly' => true, // block JavaScript access
'samesite' => 'Strict', // prevent cross-site sending
]);
Broader security measures:
- Store sessions in Redis rather than files — faster and avoids session data leaking via filesystem access
- Never store sensitive data (passwords, full credit card numbers) in sessions or cookies — sessions can be stolen, files can be read
- Rate-limit login attempts to prevent brute-forcing session IDs
- Validate
User-Agentand IP as secondary checks (though these can change legitimately, e.g., mobile networks)
Follow-up 1
What is session hijacking and how can you prevent it?
Session hijacking, also known as session stealing or session sidejacking, is an attack where an attacker gains unauthorized access to a user's session by stealing the session ID. This can be done through various means such as sniffing network traffic, cross-site scripting (XSS) attacks, or session fixation attacks.
To prevent session hijacking, you can take the following measures:
Use secure session handling techniques: Always start the session with
session_start()at the beginning of each page and regenerate the session ID after a successful login or before any sensitive operation.Implement session expiration: Set an appropriate session expiration time to limit the lifespan of a session. This reduces the window of opportunity for an attacker to hijack a session.
Use secure connections: Ensure that your website is served over HTTPS to encrypt the traffic between the client and the server, making it difficult for an attacker to intercept the session ID.
Implement IP validation and user agent validation: Validate the IP address and user agent of the client during each request to detect any suspicious activity.
Educate users about secure browsing practices: Encourage users to log out after each session, avoid using public Wi-Fi networks, and be cautious of clicking on suspicious links.
By implementing these measures, you can significantly reduce the risk of session hijacking.
Follow-up 2
What is cookie theft and how can you prevent it?
Cookie theft, also known as session cookie theft or cookie hijacking, is an attack where an attacker gains unauthorized access to a user's cookies. This can be done through various means such as cross-site scripting (XSS) attacks, session sniffing, or social engineering.
To prevent cookie theft, you can take the following measures:
Use secure cookies: When setting cookies, use the
setcookie()function with thesecureflag set to true to ensure that the cookie is only transmitted over HTTPS. Additionally, set thehttponlyflag to prevent client-side scripts from accessing the cookie.Implement secure connections: Ensure that your website is served over HTTPS to encrypt the traffic between the client and the server, making it difficult for an attacker to intercept the cookies.
Implement HTTP strict transport security (HSTS): HSTS is a security policy mechanism that allows a website to declare that it should only be accessed over HTTPS. Implementing HSTS helps prevent cookie theft by ensuring that the website is always accessed securely.
Regularly update and patch your PHP installation: Keep your PHP installation up to date with the latest security patches to protect against known vulnerabilities.
By implementing these measures, you can significantly reduce the risk of cookie theft.
Follow-up 3
What is the role of the httponly flag in PHP cookies?
The httponly flag is an important security feature in PHP cookies. When the httponly flag is set to true, it prevents client-side scripts, such as JavaScript, from accessing the cookie. This helps protect the cookie from being stolen or manipulated by malicious scripts.
By setting the httponly flag, you ensure that the cookie can only be accessed and sent to the server during HTTP requests, making it more secure against attacks like cross-site scripting (XSS).
To set the httponly flag in PHP cookies, you can use the setcookie() function with the httponly parameter set to true. For example:
setcookie('cookie_name', 'cookie_value', time() + 3600, '/', 'example.com', true, true);
In the above example, the last true parameter sets the httponly flag to true.
It is recommended to always set the httponly flag for sensitive cookies to enhance the security of your PHP application.
Live mock interview
Mock interview: PHP Sessions and Cookies
- 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.