PHP Sessions Overview Quiz

PHP
0 Passed
0% acceptance

A 40-question quiz on PHP session handling that blends policy questions and code snippets about session_start, storage, locking, regeneration, security flags, and lifecycle management.

40 Questions
~80 minutes
1

Question 1

Why do best practices require session_start to run before any HTML output?

A
Session cookies may need to send headers, and output before session_start can cause header already sent errors.
B
HTML output automatically clears $_SESSION.
C
session_start only works in CLI mode.
D
Starting after output encrypts the session.
2

Question 2

What does this counter snippet echo on the first request?

php
<?php
session_start();
if (!isset($_SESSION['hits'])) {
    $_SESSION['hits'] = 0;
}
$_SESSION['hits']++;
echo $_SESSION['hits'];
?>
A
1
B
0
C
Notice
D
hits
3

Question 3

Why should session cookies be sent with Secure and HttpOnly flags in production?

A
Secure prevents cookies from traveling over HTTP, and HttpOnly blocks JavaScript from reading them, reducing theft risk.
B
Secure encrypts the whole session payload.
C
HttpOnly makes cookies expire immediately.
D
Browsers ignore cookies without both flags.
4

Question 4

What does this session_name snippet output?

php
<?php
session_name('APPSESSID');
session_start();
echo session_name();
?>
A
APPSESSID
B
PHPSESSID
C
D
session_name
5

Question 5

Why do authentication flows regenerate the session ID immediately after login?

A
Regenerating breaks stolen or pre-login IDs, mitigating fixation attacks before privileged data is stored.
B
Regeneration deletes $_SESSION data automatically.
C
It shortens the cookie lifetime.
D
session_regenerate_id only works before login.
6

Question 6

What does this regeneration snippet echo?

php
<?php
session_start();
$_SESSION['role'] = 'user';
session_regenerate_id(true);
echo $_SESSION['role'];
?>
A
user
B
Notice
C
D
admin
7

Question 7

What does enabling session.use_strict_mode accomplish?

A
PHP refuses to accept session IDs that do not exist, preventing attackers from forcing a known ID.
B
It encrypts session data automatically.
C
It disables session_regenerate_id.
D
It forces session IDs to be sequential.
8

Question 8

What does this session_write_close snippet echo?

php
<?php
session_start();
$_SESSION['step'] = 'alpha';
session_write_close();
$_SESSION['step'] = 'beta';
echo $_SESSION['step'];
?>
A
beta
B
alpha
C
D
Notice
9

Question 9

Why should most session data remain on the server instead of storing JSON blobs in client cookies?

A
Server-side sessions keep sensitive data off the client and allow invalidation without relying on client cooperation.
B
Cookies cannot store more than 32 bytes.
C
JSON is unsupported in browsers.
D
Cookies always expire immediately.
10

Question 10

What does this cookie-param snippet echo?

php
<?php
session_set_cookie_params(['lifetime' => 3600, 'httponly' => true]);
session_start();
$params = session_get_cookie_params();
echo $params['httponly'] ? 'httpOnly' : 'default';
?>
A
httpOnly
B
default
C
3600
D
false
11

Question 11

Why does session.gc_maxlifetime not guarantee that expired sessions disappear immediately?

A
Garbage collection runs probabilistically and depends on the handler; old files may persist until GC executes.
B
gc_maxlifetime disables GC entirely.
C
Sessions never expire.
D
Handlers ignore gc_maxlifetime in CLI.
12

Question 12

What does this session_destroy snippet echo?

php
<?php
session_start();
$_SESSION['status'] = 'active';
session_destroy();
echo isset($_SESSION['status']) ? 'exists' : 'cleared';
?>
A
exists
B
cleared
C
active
D
13

Question 13

Why should logout flows call both session_unset and session_destroy before expiring the cookie?

A
Clearing the array, destroying the session data, and removing the cookie ensures no residual state persists on client or server.
B
session_destroy alone encrypts the cookie.
C
session_unset deletes database users.
D
Cookies expire automatically on logout events.
14

Question 14

What does this reopen snippet echo?

php
<?php
session_start();
$_SESSION['step'] = 'alpha';
session_write_close();
session_start();
echo $_SESSION['step'] ?? 'none';
?>
A
alpha
B
none
C
D
Notice
15

Question 15

Why should session.cookie_samesite be set to Lax or Strict on most interfaces?

A
SameSite reduces cross-site request attacks by preventing browsers from sending the session cookie on unrelated third-party requests.
B
SameSite encrypts cookies.
C
SameSite is required for HTTP traffic.
D
Browsers ignore SameSite.
16

Question 16

What does this session_id check echo once session_start runs?

php
<?php
session_start();
echo session_id() !== '' ? 'id set' : 'missing';
?>
A
id set
B
missing
C
D
session_id
17

Question 17

Why is storing megabytes of data inside $_SESSION discouraged?

A
Large sessions slow down serialization, increase lock times, and consume bandwidth when replicating across servers.
B
PHP cannot serialize arrays.
C
Large $_SESSION arrays encrypt themselves.
D
Sessions are capped at 4 KB.
18

Question 18

What does this session_save_path snippet echo?

php
<?php
session_save_path(__DIR__ . '/tmp');
session_start();
echo session_save_path();
?>
A
__DIR__/tmp
B
/tmp
C
D
files
19

Question 19

Why is session.cache_limiter often set to "private" or "nocache" for authenticated pages?

A
These settings send headers that prevent shared proxies from caching user-specific pages.
B
cache_limiter encrypts responses.
C
Public pages require nocache.
D
cache_limiter controls session IDs.
20

Question 20

What does this session_abort snippet echo?

php
<?php
session_start();
$_SESSION['cart'] = 'item';
session_abort();
echo isset($_SESSION['cart']) ? 'kept' : 'reverted';
?>
A
reverted
B
kept
C
item
D
21

Question 21

Why should production logs include session IDs only in hashed or truncated form?

A
Plain IDs in logs can be stolen to hijack sessions; hashing still lets you correlate events.
B
Logs cannot contain numbers.
C
Session IDs are already hashed.
D
Hashed IDs expire faster.
22

Question 22

Why might a project implement a custom session handler backed by Redis or a database?

A
Custom handlers allow centralized storage, replication, and eviction policies beyond the default file-based system.
B
Files cannot store session data at all.
C
Redis automatically encrypts sessions.
D
Custom handlers disable locking.
23

Question 23

What does this session_status snippet echo after session_start?

php
<?php
session_start();
echo session_status() === PHP_SESSION_ACTIVE ? 'active' : 'none';
?>
A
active
B
none
C
disabled
D
24

Question 24

Why do long-running scripts often call session_write_close before performing heavy work?

A
Closing the session releases the lock so other requests from the same user are not blocked.
B
session_write_close encrypts the session.
C
Heavy work cannot run with sessions open.
D
write_close deletes $_SESSION.
25

Question 25

What does this lifetime snippet echo?

php
<?php
session_set_cookie_params(['lifetime' => 600]);
session_start();
$params = session_get_cookie_params();
echo $params['lifetime'];
?>
A
600
B
0
C
D
lifetime
26

Question 26

Why should $_SESSION contain only essential identifiers instead of entire domain models?

A
Storing large objects increases serialization time and risk of stale data; keep sessions lean and reload data as needed.
B
$_SESSION cannot store strings.
C
Large sessions encrypt themselves.
D
Sessions must contain HTML markup.
27

Question 27

Why does preventing session fixation require rejecting session IDs supplied via URL parameters or form fields?

A
Attackers can trick victims into using a known ID; disallowing external IDs forces PHP to generate unpredictable ones.
B
URL parameters cannot hold strings.
C
Cookies are optional in PHP.
D
Fixation only affects CLI apps.
28

Question 28

What does this comparison echo after regenerating?

php
<?php
session_start();
$old = session_id();
session_regenerate_id(true);
echo $old === session_id() ? 'same' : 'changed';
?>
A
changed
B
same
C
D
Notice
29

Question 29

Why must logout processes delete the session cookie in addition to destroying server-side data?

A
If the browser keeps the cookie, it might continue sending the old ID and accidentally re-create a session.
B
Browsers only delete cookies on restart.
C
session_destroy automatically removes cookies.
D
Cookies cannot be deleted programmatically.
30

Question 30

What does this logout snippet echo after destroying the session?

php
<?php
session_start();
session_destroy();
setcookie(session_name(), '', time() - 3600);
echo session_status() === PHP_SESSION_ACTIVE ? 'active' : 'destroyed';
?>
A
destroyed
B
active
C
D
PHP_SESSION_ACTIVE
31

Question 31

Why should applications avoid storing authentication tokens in both $_SESSION and long-lived cookies simultaneously?

A
Duplicating secrets increases attack surface; pick one mechanism and rotate tokens carefully.
B
Cookies cannot store strings.
C
Sessions forbid tokens.
D
Browsers ignore duplicate values.
32

Question 32

Why is sticky session affinity in load balancers risky unless sessions are centralized?

A
If a server fails, users tied to that node lose their sessions unless the data is shared elsewhere.
B
Affinity forces browsers to restart.
C
Centralized sessions reduce performance.
D
Affinity encrypts session data.
33

Question 33

What does this AJAX-safe snippet echo?

php
<?php
session_start();
$userId = $_SESSION['user_id'] ?? null;
session_write_close();
echo $userId ? 'loaded' : 'guest';
?>
A
loaded
B
guest
C
Notice
D
34

Question 34

What does this cache-limiter snippet echo?

php
<?php
session_cache_limiter('private_no_expire');
session_start();
echo session_cache_limiter();
?>
A
private_no_expire
B
nocache
C
D
public
35

Question 35

What does session_status() returning PHP_SESSION_DISABLED indicate?

A
Sessions are disabled in php.ini or the SAPI, so session_start cannot be used.
B
Sessions are currently active.
C
session_start succeeded.
D
The session expired.
36

Question 36

Why should session.cookie_path usually match the application base path?

A
Restricting the cookie to the relevant path avoids leaking it to unrelated parts of the host that do not need access.
B
cookie_path encrypts the cookie.
C
Browsers ignore cookies without /.
D
cookie_path determines cookie lifetime.
37

Question 37

What does this handler inspection echo by default?

php
<?php
session_start();
echo ini_get('session.save_handler');
?>
A
files
B
redis
C
user
D
38

Question 38

Why do some frameworks store only a session identifier for the logged-in user and fetch roles from the database on each request?

A
Fetching fresh data avoids stale permissions and keeps sessions small.
B
Sessions cannot store integers.
C
Databases cannot change roles after login.
D
Frameworks do not support $_SESSION.
39

Question 39

Why is it important to release the session lock before performing third-party API calls within a request?

A
Holding the lock during slow network calls blocks other tabs from processing their own requests, hurting UX.
B
API calls cannot run with sessions open.
C
Locks encrypt responses.
D
Third-party APIs require released locks.
40

Question 40

Why should CLI scripts avoid starting sessions unless they coordinate with web requests?

A
Sessions introduce unnecessary file locks and state when most CLI tasks can store transient data elsewhere.
B
session_start fails in CLI.
C
CLI scripts cannot read $_SESSION.
D
Sessions delete environment variables.

QUIZZES IN PHP