PHP Cookie Handling Essentials Quiz

PHP
0 Passed
0% acceptance

A 35-question quiz that examines how PHP applications set, scope, secure, and debug cookies for personalization, analytics, and authentication touchpoints.

35 Questions
~70 minutes
1

Question 1

During a login callback, why do reviewers insist on calling setcookie before echoing any template output or UTF-8 BOM?

A
Cookies travel in HTTP headers, so emitting body content first can prevent PHP from sending new Set-Cookie headers.
B
Cookies only work when echoed inside HTML tables.
C
Calling setcookie late deletes every existing cookie.
D
setcookie requires an open database connection before it runs.
2

Question 2

A teammate captured this snippet after the controller finished processing. What does it echo?

php
<?php
    $result = setcookie('theme', 'dark', time() + 3600, '/');
    echo $result ? 'queued' : 'failed';
    ?>
A
queued
B
failed
C
dark
D
0
3

Question 3

Analytics wants to stuff tracking metadata into a single cookie. Why do architects cap each cookie at roughly 4 KB?

A
Browsers enforce per-cookie limits near 4 KB, so oversize values are truncated or ignored, wasting requests.
B
Cookies larger than 4 KB are automatically encrypted by PHP.
C
Cookies smaller than 4 KB cannot be deleted.
D
The HTTP spec bans multiple cookies if one exceeds 4 KB.
4

Question 4

Given this request-scoped snippet, what is rendered?

php
<?php
    $_COOKIE['locale'] = 'fr-CA';
    echo $_COOKIE['locale'] ?? 'fallback';
    ?>
A
fr-CA
B
fallback
C
locale
D
Notice
5

Question 5

Why do browser vendors require the Secure flag whenever SameSite=None is used for cross-site flows?

A
SameSite=None allows cookies on third-party requests, so Secure ensures they only travel over HTTPS to prevent interception.
B
Secure adds CSRF validation automatically when SameSite=None is present.
C
SameSite=None disables cookies unless Secure is off.
D
Secure converts the cookie to an HTTP header.
6

Question 6

Look at this diagnostic snippet executed during a request that already contains a feature cookie. What prints?

php
<?php
    $_COOKIE['feature'] = 'beta';
    setcookie('feature', 'stable', time() + 3600);
    echo $_COOKIE['feature'];
    ?>
A
beta
B
stable
C
Notice
D
feature
7

Question 7

Product wants to keep structured preferences in one cookie. Why is storing a JSON string safer than serializing PHP objects directly?

A
JSON is language-agnostic and avoids PHP object injection risks if the string is echoed back or parsed elsewhere.
B
JSON automatically encrypts the payload.
C
PHP objects cannot be stored inside cookies at all.
D
Browsers convert JSON to environment variables.
8

Question 8

An engineer tests immediate availability of a freshly set cookie. What does this snippet echo?

php
<?php
    setcookie('promo', 'BOGO', ['expires' => time() + 600, 'path' => '/deals']);
    echo isset($_COOKIE['promo']) ? 'present' : 'not yet';
    ?>
A
not yet
B
present
C
BOGO
D
Notice
9

Question 9

Why does setting the cookie domain to .acme.fm matter when multiple subdomains share authentication?

A
A leading dot scopes the cookie to all subdomains, letting api.acme.fm and dashboard.acme.fm reuse the same token.
B
The dot encrypts the cookie contents.
C
Without a dot, PHP refuses to send cookies.
D
Browsers ignore cookies with dots in the domain.
10

Question 10

Security requested that every sensitive cookie be marked HttpOnly. What problem does that flag reduce?

A
HttpOnly prevents JavaScript from reading the cookie, making XSS-based theft harder.
B
HttpOnly forces the cookie to expire after one minute.
C
HttpOnly lets Service Workers sync cookies offline.
D
HttpOnly disables SameSite.
11

Question 11

A controller guards against template fragments that might have already flushed output. What does this diagnostic snippet echo when no output was sent yet?

php
<?php
    if (headers_sent()) {
        echo 'fallback';
    } else {
        setcookie('ab', 'A');
        echo 'queued';
    }
    ?>
A
queued
B
fallback
C
ab
D
Notice
12

Question 12

Why do platform teams standardize cookie paths (for example, /app versus /) even when the app only uses one route today?

A
Explicit paths limit where the browser sends the cookie, preventing unrelated tools on the same host from seeing it later.
B
Paths change the cookie encryption key.
C
Browsers delete cookies without a custom path.
D
PHP ignores cookies when the path is /.
13

Question 13

Why should sensitive cookie values (session IDs, CSRF secrets) never be logged verbatim even during debugging?

A
Log storage is often less protected than production DBs, so captured tokens could later be replayed.
B
Logs cannot store strings longer than 32 characters.
C
Logging cookies deletes them from the browser.
D
Cookie values are already hashed inside logs.
14

Question 14

How does this snippet interpret a structured cookie string?

php
<?php
    $_COOKIE['prefs'] = 'lang=en&tz=utc';
    parse_str($_COOKIE['prefs'], $prefs);
    echo $prefs['lang'] ?? 'none';
    ?>
A
en
B
tz=utc
C
none
D
Notice
15

Question 15

Why do teams avoid setting Secure=false on production cookies even for anonymous tracking?

A
Without Secure, cookies leak over HTTP downgrades, letting attackers tamper with segments or impersonate users.
B
Secure=false disables SameSite entirely.
C
Secure=false deletes the cookie on Chrome but not Firefox.
D
Browsers refuse to store non-Secure cookies.
16

Question 16

During privacy reviews, why do architects forbid copying entire user profiles into cookies for offline access?

A
Cookies are user-controlled and travel on every request, so large or sensitive payloads increase exposure and bandwidth costs.
B
Cookies are encrypted, making data retrieval impossible.
C
Browsers cannot delete cookies with sensitive data.
D
Cookies do not support UTF-8 strings.
17

Question 17

A migration splits a large value into multiple cookie chunks for legacy browsers. What does this snippet print?

php
<?php
    $payload = str_repeat('x', 3000);
    $chunks = str_split($payload, 1000);
    foreach ($chunks as $index => $chunk) {
        setcookie('report_' . $index, $chunk, 0, '/');
    }
    echo count($chunks);
    ?>
A
3
B
1
C
0
D
3000
18

Question 18

Why do logout flows call setcookie with an expiration in the past as well as clearing server-side state?

A
Setting expires to time()-3600 instructs the browser to remove the cookie immediately, ensuring the client stops sending the ID.
B
Past expirations encrypt the cookie.
C
Browsers ignore future expirations.
D
PHP refuses to delete cookies without a DB call.
19

Question 19

Compliance asks for input validation on cookies before use. Which PHP API is most helpful for pulling a sanitized value?

A
filter_input(INPUT_COOKIE, 'name', FILTER_SANITIZE_SPECIAL_CHARS)
B
phpinfo()
C
ini_get('allow_url_fopen')
D
curl_exec()
20

Question 20

How many seats does this snippet report when the cookie arrives as a numeric string?

php
<?php
    $_COOKIE['seats'] = '12';
    echo (int) $_COOKIE['seats'] + 3;
    ?>
A
15
B
123
C
12
D
Notice
21

Question 21

Why might a shared domain leave the cookie domain attribute blank even when subdomains exist?

A
Leaving it blank scopes the cookie to the exact host, preventing unrelated subdomains from receiving privileged state.
B
Blank domains encrypt the cookie contents.
C
Browsers require blank domains for HttpOnly.
D
Subdomains cannot set cookies if the domain is blank.
22

Question 22

Frameworks often wrap setcookie inside response objects. Why do they still expose low-level cookie option maps?

A
Engineers need fine-grained control over expires, path, domain, and SameSite to satisfy diverse endpoints.
B
Option maps encrypt the cookie contents.
C
PHP ignores cookies unless arrays are passed.
D
Headers cannot be set without option objects.
23

Question 23

What does this snippet output after decoding a JSON preference cookie?

php
<?php
    $_COOKIE['ui'] = '{"density":"compact","color":"midnight"}';
    $prefs = json_decode($_COOKIE['ui'], true);
    echo $prefs['color'] ?? 'default';
    ?>
A
midnight
B
compact
C
default
D
Notice
24

Question 24

Why do internationalized sites store only a locale code in cookies instead of the entire translation catalog?

A
Locale codes are small and let the server decide which resource bundle to load, avoiding massive cookie payloads.
B
Cookies cannot contain Unicode letters.
C
Translation catalogs must live in localStorage.
D
Locale cookies cannot be deleted.
25

Question 25

Support asks whether to use expires or max-age when setting cookies. Why do many teams prefer max-age when supported?

A
max-age expresses lifetime relative to the current moment, avoiding timezone mistakes that can arise with formatted expires strings.
B
max-age encrypts the cookie.
C
expires is banned on mobile browsers.
D
max-age forces SameSite=Strict.
26

Question 26

How does this snippet validate numeric cookies before use?

php
<?php
    $_COOKIE['cart_qty'] = '7';
    $qty = filter_var($_COOKIE['cart_qty'], FILTER_VALIDATE_INT);
    echo $qty === false ? 'invalid' : $qty;
    ?>
A
7
B
invalid
C
cart_qty
D
Notice
27

Question 27

Why should CSRF tokens live in HttpOnly, same-site cookies instead of JavaScript-accessible storage?

A
HttpOnly cookies cannot be read by injected scripts, reducing the blast radius of XSS while still letting the browser attach the token automatically.
B
JavaScript cannot read any storage APIs.
C
Cookies are required for every POST request.
D
Browsers delete localStorage every hour.
28

Question 28

A product surface posts forms back to the same domain. Why is SameSite=Lax usually acceptable for its session cookie?

A
SameSite=Lax allows cookies on top-level navigations and GET requests, which covers typical same-domain form submits without cross-site risks.
B
Lax encrypts cookies.
C
Lax forces cookies to expire after one hour.
D
Browsers ignore cookies with other SameSite values.
29

Question 29

Why do security guides recommend hashing remember-me tokens before storing them in cookies?

A
Hashing prevents attackers who steal a cookie from learning the original token used in the database, enabling one-way comparison only.
B
Hashing shortens the cookie automatically.
C
Browsers require hashes for cookies.
D
Hashing forces SameSite=None.
30

Question 30

A middleware signs cookie values to detect tampering. What does this snippet echo?

php
<?php
    $secret = 'build-2025';
    $_COOKIE['state'] = 'page=pricing';
    $signature = hash_hmac('sha256', $_COOKIE['state'], $secret);
    echo strlen($signature);
    ?>
A
64
B
32
C
0
D
Notice
31

Question 31

Why do logout pages often clear both authentication and auxiliary personalization cookies?

A
Removing all user-specific cookies ensures the next visitor on a shared device does not inherit preferences or hints tied to the previous user.
B
Browsers crash if more than one cookie is cleared at once.
C
Personalization cookies cannot outlive sessions.
D
Deleting multiple cookies encrypts traffic.
32

Question 32

When would setrawcookie be preferred over setcookie for the same value?

A
When the value is already URL-encoded and you do not want PHP to re-encode reserved characters.
B
When you need automatic encryption.
C
When cookies must be stored server-side.
D
When the browser is offline.
33

Question 33

Why do multi-region platforms document cookie behavior per environment (staging, EU, US) even when code is shared?

A
Different domains, certificates, or CDN layers may require distinct cookie scopes and flags despite identical PHP logic.
B
Cookies only work in one country at a time.
C
PHP needs separate functions per region.
D
Browsers ignore documentation.
34

Question 34

Why should teams monitor response headers after CDN or WAF changes?

A
Intermediaries can inject, strip, or reorder Set-Cookie headers, so monitoring ensures security flags survive the edge.
B
CDNs automatically delete all cookies.
C
WAFs convert cookies into POST bodies.
D
Headers are irrelevant once TLS is enabled.
35

Question 35

Why do incident responders keep a playbook for clearing or rotating cookies after breaches?

A
Coordinated rotation (server invalidation plus forced client deletion) stops hijacked cookies from being reused during the incident window.
B
Cookies cannot be rotated without a playbook.
C
Regulators require deleting all cookies nightly.
D
Playbooks encrypt headers.

QUIZZES IN PHP