PHP Input Handling Quiz

PHP
0 Passed
0% acceptance

A 30-question quiz on PHP input handling that balances code review scenarios and short snippets covering validation, sanitization, filtering, and consistent error handling for web and CLI inputs.

30 Questions
~60 minutes
1

Question 1

Why does guidance often insist on validating inputs at the perimeter of a controller rather than inside deep utility classes?

A
Validating once at the edge ensures downstream code can assume inputs are clean, reducing repetitive guards.
B
Utility classes cannot access superglobals.
C
Input validation only works in controllers.
D
Perimeter validation encrypts data automatically.
2

Question 2

What does this snippet echo when /api.php?id=42?

php
<?php
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
echo $id === false ? 'invalid' : $id;
?>
A
42
B
invalid
C
D
id
3

Question 3

Why should scripts treat filter_input returning null differently from false?

A
null means the field was missing, while false means it existed but failed validation, and error messages should reflect that difference.
B
null indicates the server crashed.
C
false is only returned in CLI mode.
D
null disables headers.
4

Question 4

What does this POST handler echo when the email field is absent?

php
<?php
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
echo $email === null ? 'missing' : ($email === false ? 'invalid' : 'ok');
?>
A
missing
B
invalid
C
ok
D
5

Question 5

Why do teams prefer hash_equals when comparing API tokens from $_SERVER["HTTP_X_TOKEN"]?

A
hash_equals performs a timing-safe comparison, preventing attackers from measuring response time differences.
B
hash_equals logs comparisons automatically.
C
Timing attacks only target databases.
D
Hash comparisons cannot be unit tested.
6

Question 6

What does this CSRF token check echo?

php
<?php
$token = $_POST['csrf'] ?? '';
echo hash_equals($_SESSION['csrf'] ?? '', $token) ? 'pass' : 'fail';
?>
A
pass
B
fail
C
csrf
D
7

Question 7

Why do review guidelines prefer filter_input(INPUT_SERVER, "HTTP_X_FORWARDED_PROTO") over direct $_SERVER checks when proxies are involved?

A
filter_input can apply sanitization and ensures the key exists before use, reducing risk of undefined indexes.
B
$_SERVER cannot be read after session_start.
C
HTTP headers require filter_input to decrypt.
D
Proxies automatically sanitize headers.
8

Question 8

What does this request-method gate echo when the client sends POST?

php
<?php
echo $_SERVER['REQUEST_METHOD'] === 'POST' ? 'process' : 'ignore';
?>
A
process
B
ignore
C
POST
D
9

Question 9

Why is json_decode($body, true, 512, JSON_THROW_ON_ERROR) considered safer than silent decoding when handling JSON payloads?

A
Throwing errors prevents invalid JSON from masquerading as an empty array and makes problems visible to logs or callers.
B
json_decode without flags returns XML.
C
JSON_THROW_ON_ERROR turns JSON into objects automatically.
D
json_decode cannot parse UTF-8 without that flag.
10

Question 10

What does this JSON handler echo when the payload is {"name":"Ops"}?

php
<?php
$data = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);
echo $data['name'] ?? 'missing';
?>
A
Ops
B
missing
C
D
name
11

Question 11

Why do form-handling controllers typically trim and normalize whitespace before validation?

A
Users often add accidental spaces; trimming avoids false negatives without altering meaningful content.
B
Whitespace breaks PHP arrays.
C
Validation libraries cannot read untrimmed strings.
D
Trimming encrypts the string.
12

Question 12

What does this sanitization snippet echo?

php
<?php
$raw = "  [email protected]  ";
$clean = filter_var(trim($raw), FILTER_VALIDATE_EMAIL);
echo $clean ?: 'invalid';
?>
13

Question 13

Why do payment endpoints often reject inputs containing control characters even if they pass regex validation?

A
Control characters can break logs, downstream APIs, or JSON serialization, so removing them prevents subtle attacks.
B
Control characters are required for UTF-8.
C
Regex cannot detect control characters.
D
Payment gateways forbid uppercase letters.
14

Question 14

What does this control-character filter output?

php
<?php
$input = "order	123";
if (preg_match('/[-]/', $input)) {
    echo 'reject';
} else {
    echo 'accept';
}
?>
A
reject
B
accept
C
order123
D
15

Question 15

Why is it recommended to log raw inputs separately from sanitized values when debugging?

A
Logs should show both what was received and what was accepted so analysts can see what was removed or rejected.
B
Sanitized values cannot be logged.
C
Raw inputs are encrypted automatically.
D
Sanitized values break log rotation.
16

Question 16

What does this raw-vs-sanitized logger echo?

php
<?php
$raw = $_GET['sku'] ?? '';
$clean = preg_replace('/[^A-Za-z0-9_-]/', '', $raw);
echo $raw . ' -> ' . $clean;
?>
A
user input followed by the cleaned version
B
Only the cleaned value
C
Only the raw value
D
Nothing
17

Question 17

Why is filter_var with FILTER_VALIDATE_BOOL and FILTER_NULL_ON_FAILURE handy for checkbox inputs?

A
It differentiates true/false strings from unexpected values by returning null when input is not recognizable.
B
Checkboxes cannot post integers.
C
FILTER_VALIDATE_BOOL encrypts the result.
D
It converts booleans to arrays.
18

Question 18

What does this boolean filter echo when $_POST["active"]="on"?

php
<?php
$active = filter_var($_POST['active'] ?? null, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE);
echo $active === null ? 'invalid' : ($active ? 'true' : 'false');
?>
A
true
B
false
C
invalid
D
19

Question 19

Why should CLI scripts validate $argv length before accessing arguments?

A
Accessing missing indexes triggers notices and makes error messages unclear; checking upfront lets scripts show usage instructions.
B
CLI arguments are always encrypted.
C
PHP ignores argv in cron jobs.
D
Array indexes change order between runs.
20

Question 20

What does this CLI validator echo when no argument is provided?

php
<?php
if ($argc < 2) {
    echo "usage: php script.php <name>";
    exit;
}
echo $argv[1];
?>
A
usage: php script.php <name>
B
script.php
C
<name>
D
21

Question 21

Why is it useful to centralize input parsing in a Request object or helper class?

A
Centralizing parsing makes mocking easier, keeps controllers consistent, and allows automated sanitization before data spreads.
B
Request objects encrypt values.
C
Helpers cannot read $_POST.
D
It forces everything into JSON.
22

Question 22

What does this Request helper usage echo?

php
<?php
class Request {
    public function input(string $key, $default = null) {
        return $_POST[$key] ?? $_GET[$key] ?? $default;
    }
}
$request = new Request();
echo $request->input('q', 'none');
?>
A
none (when q is missing) or the provided value
B
null
C
q
D
Request
23

Question 23

Why should file upload handlers enforce a maximum size before calling move_uploaded_file?

A
Validating size prevents exhausting disk space or memory and lets the app respond gracefully when a file is too large.
B
move_uploaded_file refuses small files.
C
$_FILES cannot report filesize.
D
PHP deletes files larger than 1 MB automatically.
24

Question 24

What does this size check echo when an uploaded file is 5 MB and the limit is 2 MB?

php
<?php
$file = $_FILES['doc'] ?? null;
$limit = 2 * 1024 * 1024;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
    echo 'error';
} elseif ($file['size'] > $limit) {
    echo 'too large';
} else {
    echo 'ok';
}
?>
A
too large
B
ok
C
error
D
5
25

Question 25

Why should CLI scripts reading STDIN check stream metadata before assuming the input is textual?

A
Binary data or large streams may not be safe to echo directly; checking metadata helps avoid corrupt output or memory spikes.
B
STDIN always contains JSON.
C
PHP refuses to read STDIN without metadata.
D
Stream metadata disables buffering.
26

Question 26

What does this STDIN reader echo when input is "hello"?

php
<?php
$stdin = trim(stream_get_contents(STDIN));
echo $stdin ?: 'empty';
?>
A
hello
B
empty
C
D
STDIN
27

Question 27

Why do APIs respond with HTTP 422 or 400 when required input fields are missing?

A
Clear status codes help clients fix requests and keep server logs easier to search.
B
422 automatically retries requests.
C
400 responses never include bodies.
D
Missing fields crash PHP unless 422 is used.
28

Question 28

What does this response builder echo when required fields are absent?

php
<?php
$payload = json_decode(file_get_contents('php://input'), true);
if (empty($payload['name'])) {
    http_response_code(422);
    echo 'missing name';
    exit;
}
echo 'ok';
?>
A
missing name
B
ok
C
422
D
29

Question 29

Why should controllers log invalid input payloads with correlation IDs rather than plain text messages?

A
Correlation IDs tie logs back to requests, easing debugging and auditing when multiple inputs fail.
B
Plain text logs are illegal.
C
Correlation IDs encrypt the payload.
D
Logging invalid input is not useful.
30

Question 30

What does this logging helper echo when it captures a bad payload?

php
<?php
$correlationId = $_SERVER['HTTP_X_REQUEST_ID'] ?? uniqid('req_', true);
$payload = $_POST ?: [];
echo $correlationId . ':' . json_encode($payload);
?>
A
Generated or provided request ID followed by JSON payload
B
Only the payload
C
Only the ID
D
Error

QUIZZES IN PHP