40 questions / 10 random questions
Random questions, instant feedback, and review for missed questions.
View recommended PHP resources →
In PHP, you want to read an optional configuration key and use a default value without warnings when the key is missing. Which expression is most natural?
Answer: $config['timezone'] ?? 'UTC'
The null coalescing operator ?? returns the right side when the left side is missing or null. It is suitable for default values on optional array keys.
In a PHP template that displays form input in HTML, what is the most basic measure to avoid XSS?
Answer: Escape output with htmlspecialchars when rendering HTML
When rendering user input into HTML, output escaping is fundamental. htmlspecialchars converts special HTML characters to entities.
You want stricter scalar argument type handling in a PHP file. Which declaration should be placed at the top of the file?
Answer: declare(strict_types=1);
declare(strict_types=1); makes scalar type handling stricter for calls made from that file. Be aware of boundaries with existing code.
You want to refer to the namespaced class App\Service\Mailer as Mailer. Which statement is appropriate?
Answer: use App\Service\Mailer;
use imports namespaced classes or functions so they can be referenced with shorter names.
You want to handle a JSON API response as an associative array. Which json_decode call is appropriate?
Answer: json_decode($json, true)
json_decode($json, true) returns JSON objects as associative arrays. With false or the default, they are returned as standard objects.
In PHP, you want to store user IDs as keys and user names as values. Which data structure is most appropriate?
Answer: Associative array
PHP arrays can act as ordered maps. An associative array is natural when looking up values by user ID.
A function may return a string or null. Which PHP 8 style return type is natural?
Answer: ?string
?string is a nullable type equivalent to string|null. It should not be mixed with void for a value-returning function.
You need to process a large dataset item by item without loading everything into memory. Which PHP mechanism is a good candidate?
Answer: Generator with yield
Generators produce values lazily, which helps when iterating without building a large array.
In PHP 8, which exception type should you consider catching when an invalid type is passed to an internal function?
Answer: TypeError
PHP 8 may throw TypeError for arguments of invalid type. ValueError is also relevant when a value itself is invalid.
You want cleanup such as closing a file handle to run even if an exception occurs. Which construct is appropriate?
Answer: try / catch / finally
A finally block runs whether or not an exception occurs, making it suitable for resource cleanup.
What is an appropriate purpose of setting a default value for a function parameter?
Answer: To define behavior when omitted and keep call sites concise
Default parameters express common default behavior in the function definition. They do not replace security or exception handling.
For a function that accepts a callback, which type declaration most clearly expresses the intent?
Answer: callable
callable expresses that the value can be invoked, such as a function name, closure, or method reference.
In Composer, which file mainly records project dependencies and version constraints?
Answer: composer.json
composer.json contains project definitions such as dependencies, autoload settings, and scripts.
In CI or production deployment, you want to install the exact versions pinned in composer.lock. Which command is appropriate?
Answer: composer install
composer install installs dependencies according to the lock file when present. update recalculates dependency versions.
You want PSR-4 autoloading to map the App\ namespace to src/. Where should this be configured?
Answer: The autoload section of composer.json
Composer PSR-4 autoloading is defined in the autoload section of composer.json, then regenerated with composer dump-autoload when needed.
You do not want development tools installed in a production image. Which Composer install option is representative?
Answer: composer install --no-dev
--no-dev excludes require-dev dependencies. It helps reduce production build size and attack surface.
In a PHP app that executes SQL using user input, what is a basic SQL injection mitigation?
Answer: Use PDO prepared statements with bound values
For SQL, placeholders and bound values separate SQL structure from data. HTML escaping is for HTML output.
Which PHP API pair is fundamental for storing and verifying passwords?
Answer: password_hash / password_verify
password_hash creates a secure password hash, and password_verify checks a password against a hash.
As a basic defense against session fixation, what should be done immediately after successful login?
Answer: Call session_regenerate_id(true)
Regenerating the session ID when privilege state changes, such as login, reduces the risk of abusing a fixed ID. The true argument deletes the old session data, which is the recommended approach.
What is a risk of using the original user-supplied filename directly as the stored filename in an upload feature?
Answer: It may lead to path traversal, overwrites, or dangerous extensions
Uploads require generated storage names, extension and MIME validation, separated storage locations, and exposure controls.
Which opening tag is basically used to have code interpreted as PHP in a PHP file?
Answer: <?php
PHP code usually starts with <?php. When PHP is embedded in HTML, the code after this tag is interpreted as PHP.
Which symbol is used at the start of a PHP variable name?
Answer: $
PHP variables start with $, such as $name. Variable names are case-sensitive, so $user and $User are different variables.
Which basic PHP type is appropriate for handling multiple values together?
Answer: array
array is a type for handling multiple values together. It can represent both numeric-indexed arrays and key-value pairs.
You want PHP to run different code depending on a condition. Which is the most basic construct?
Answer: if
if is the basic construct for branching based on whether a condition is true or false. It can be combined with else or elseif.
Which PHP superglobal is basically used to receive a value passed in a URL query string such as ?page=2?
Answer: $_GET
$_GET is the superglobal for URL query string values. Values received from users should be validated or escaped according to their usage.
You accept an age value that must be an integer within a valid range. Which PHP input-handling approach is appropriate?
Answer: Validate the type with a function such as filter_var, then check the allowed range
Input validation should confirm the expected type or format and then enforce business constraints. Sanitizing a value and deciding whether it is acceptable are different operations.
You need an unpredictable token for a password-reset URL in PHP. Which function is appropriate?
Answer: random_bytes
random_bytes generates cryptographically secure random bytes. For URLs, encode the bytes safely and also enforce expiration and one-time use.
You compare a received webhook signature with a server-computed signature. Which function helps reduce timing-attack leakage?
Answer: hash_equals
hash_equals compares a known signature with a user-supplied signature in a timing-attack-resistant manner. Correct HMAC generation and secret management are also required.
You need to decode data supplied by an external user in PHP. Which basic approach avoids object-injection risk?
Answer: Avoid unserialize for untrusted values and use a format such as JSON that represents only needed data types
Calling unserialize on untrusted serialized data can lead to object injection through class magic methods. Prefer explicit data formats such as JSON for external data.
In production PHP, you want to hide stack traces and internal paths from users while retaining information for troubleshooting. Which configuration approach is appropriate?
Answer: Disable display_errors, enable log_errors, and write to protected logs
Production systems should hide detailed errors from users and record them in access-controlled logs. Return generic error responses and avoid placing excessive sensitive data in logs.
With Composer, you want to install dependencies in production without development packages. Which command is appropriate?
Answer: composer install --no-dev
composer install --no-dev installs only production dependencies according to composer.lock. Production deployments should preserve reproducible dependency versions.
When executing SQL with user input from PHP, which measure is most appropriate against SQL injection?
Answer: Use PDO prepared statements and bind values to placeholders
Prepared statements separate SQL syntax from values and are a core SQL injection defense. HTML escaping is for HTML output, not SQL context.
With PDO, you want database failures to be handled as exceptions. Which connection attribute is appropriate?
Answer: Set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION
Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION makes database errors easier to handle as exceptions and clarifies failure control flow.
After successful login, which basic PHP action helps reduce session fixation risk?
Answer: Regenerate the session ID with session_regenerate_id(true)
When privilege state changes, such as after login, regenerate the session ID to reduce the risk of continuing an attacker-fixed ID.
When accepting image uploads in PHP, which basic safety measure is appropriate?
Answer: Inspect content rather than relying only on MIME/extension, generate a stored name, and save where it cannot be executed publicly
Uploads require size limits, content inspection, generated storage names, no execute permission, and controlled public paths. User-provided names and extensions are not trustworthy.
In PHP exception handling, which basic construct catches exceptions for logging or fallback processing?
Answer: try ... catch
try ... catch wraps code that may throw and handles exceptions in the catch block through logging, rollback, or user-facing responses.
In PHP, you want to explicitly indicate that a function returns no value. Which return type is appropriate?
Answer: void
void indicates that a function returns no value. null is a value and differs from returning no value.
In PHP, you want to handle date and time with timezone awareness and perform addition or comparison safely. Which class combination is appropriate?
Answer: DateTimeImmutable and DateTimeZone
DateTimeImmutable with DateTimeZone lets you handle date and time with explicit timezones. Immutable values also help avoid unintended mutation.
You want to apply the same transformation to each array element and get a new array. Which PHP function is appropriate?
Answer: array_map
array_map applies a callback to each element and builds a new array. Use array_filter for filtering and array_reduce for folding.
When returning a JSON API response from PHP, which Content-Type is most appropriate?
Answer: application/json
A JSON API should send Content-Type: application/json so clients can correctly interpret the response format.