Sessions, Cookies & State Management
Master stateless protocol state management. Secure and handle user sessions, cookies, session hijacking, and CSRF protection.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is the difference between sessions and cookies in PHP?
Both are ways to persist data across HTTP requests, but they store data in different places and serve different purposes.
| Aspect | Cookie | Session |
|---|---|---|
| Storage location | Client-side (browser memory or disk) | Server-side (files, database, or cache) |
| Data size limit | ~4KB per cookie | Unlimited |
| Best for | Non-sensitive data | User login state, sensitive data |
Q2. How do you start and use sessions in PHP?
Call session_start() at the very beginning of your script (before any output).
session_start();
if (isset($_POST['login'])) {
$_SESSION['user_id'] = $userId;
}
if (isset($_SESSION['user_id'])) {
echo 'Welcome';
}
Q3. What is session fixation and how do you prevent it?
Session fixation is when an attacker forces a user to use a known session ID. Prevent it by regenerating the session ID on login.
if (validate_credentials($username, $password)) {
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
}
Q4. How do you set and retrieve cookies in PHP?
setcookie('user_preference', 'dark_mode', [
'expires' => time() + (30 * 24 * 60 * 60),
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
echo $_COOKIE['user_preference'] ?? 'light_mode';
Q5. What is the difference between session_destroy() and session_unset()?
| Function | What it does |
|---|---|
| session_unset() | Clears $_SESSION values only |
| session_destroy() | Deletes entire session file |
Q6. How do you configure session handling in php.ini?
| Directive | Purpose |
|---|---|
| session.save_handler | Where to store sessions |
| session.gc_maxlifetime | Session timeout in seconds |
| session.cookie_secure | Only send over HTTPS |
| session.cookie_httponly | Hide from JavaScript |
Q7. What is session hijacking and how do you prevent it?
Session hijacking is when an attacker steals a valid session ID. Prevent by using HTTPS, httponly flag, and regenerating IDs on login.
| Attack vector | Prevention |
|---|---|
| Network interception | Use HTTPS with secure flag |
| XSS | Set httponly flag |
Q8. How do you implement remember-me functionality?
Store a secure token in database and set a long-lived cookie. On subsequent visits, validate the token before logging in.
$token = bin2hex(random_bytes(32));
$db->query('INSERT INTO remember_tokens (user_id, token, expires) VALUES (?, ?, ?)',
[$user_id, hash('sha256', $token), time() + (30 * 24 * 60 * 60)]);
setcookie('remember_token', $token, ['secure' => true, 'httponly' => true]);
Q9. How do you prevent CSRF attacks?
CSRF happens when an attacker makes a user unknowingly send requests. Main defense is a CSRF token in forms.
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF token mismatch');
}
Q10. How do you use cookies with different domains and paths?
setcookie('admin_token', $token, [
'path' => '/admin',
'secure' => true,
'httponly' => true
]);
setcookie('user_id', $id, [
'domain' => '.example.com',
'secure' => true
]);| Property | Purpose |
|---|---|
| path | Only send for requests to this path |
| domain | Restrict to domain and subdomains |
Sessions, Cookies & State Management
Master stateless protocol state management. Secure and handle user sessions, cookies, session hijacking, and CSRF protection.
What is the difference between sessions and cookies in PHP?
Both are ways to persist data across HTTP requests, but they store data in different places and serve differen...
How do you start and use sessions in PHP?
Call session_start() at the very beginning of your script (before any output).session_start(); if (isset($_POS...
What is session fixation and how do you prevent it?
Session fixation is when an attacker forces a user to use a known session ID. Prevent it by regenerating the s...
How do you set and retrieve cookies in PHP?
setcookie('user_preference', 'dark_mode', [ 'expires' => time() + (30 * 24 * 60 * 60), 'secure' => tru...
What is the difference between session_destroy() and session_unset()?
FunctionWhat it doessession_unset()Clears $_SESSION values onlysession_destroy()Deletes entire session file
How do you configure session handling in php.ini?
DirectivePurposesession.save_handlerWhere to store sessionssession.gc_maxlifetimeSession timeout in secondsses...
What is session hijacking and how do you prevent it?
Session hijacking is when an attacker steals a valid session ID. Prevent by using HTTPS, httponly flag, and re...
How do you implement remember-me functionality?
Store a secure token in database and set a long-lived cookie. On subsequent visits, validate the token before...
How do you prevent CSRF attacks?
CSRF happens when an attacker makes a user unknowingly send requests. Main defense is a CSRF token in forms.if...
How do you use cookies with different domains and paths?
setcookie('admin_token', $token, [ 'path' => '/admin', 'secure' => true, 'httponly' => true ]); se...