80 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.
An API must distinguish the user ID string "00123" from the integer 123. Which comparison is appropriate?
Answer: Use the strict comparison operator === to compare both type and value
PHP loose comparison performs type coercion and can make distinct identifiers compare equal. When validating external input or state values, include the type in the contract and use ===.
In PHP 8.1+, you want an order status that accepts only pending, paid, or cancelled. Which design is appropriate?
Answer: Define a string-backed enum and convert at the boundary with a method such as tryFrom
An enum limits valid states in the type system. Convert external strings to the enum at the application boundary and treat conversion failure as invalid input so unsupported states do not spread internally.
You want an API request DTO to remain unchanged after construction. In PHP 8.2+, which choice is appropriate?
Answer: Define a readonly class with required properties and pass validated values through its constructor
A readonly class prevents property reassignment after initialization and helps preserve DTO invariants. It does not automatically make referenced objects deeply immutable, so member types still require review.
When an external API returns malformed JSON, you want to distinguish it from a valid JSON null and route failure through exception handling. What should you do?
Answer: Pass JSON_THROW_ON_ERROR to json_decode and handle JsonException
With JSON_THROW_ON_ERROR, JSON syntax and encoding failures throw JsonException. This avoids confusing a valid null value with failure and makes API error handling explicit.
A PHP web form must prevent CSRF, where another site triggers an unintended update using the user's authority. What is the central defense?
Answer: Issue an unpredictable CSRF token bound to the session and verify it on state-changing requests
CSRF protection binds a token unavailable to the attacking origin to the user's session and verifies it on state changes. SameSite cookies and Origin checks add defense in depth but do not automatically replace token validation for every application.
You want to harden session cookies for a PHP application served only over HTTPS. Which attribute combination is fundamental?
Answer: Set Secure, HttpOnly, and an appropriate SameSite value before session_start
Secure limits cookie transmission to HTTPS, HttpOnly restricts JavaScript access, and SameSite controls cross-site sending. In PHP, configure session cookie parameters before starting the session.
After a PHP upgrade, the recommended password hash algorithm or cost has changed. How should hashes be migrated safely during login?
Answer: After password_verify succeeds, call password_needs_rehash and update the hash when needed
After successful verification, the plaintext input is temporarily available. Check the stored hash with password_needs_rehash and progressively replace only outdated hashes with a new password_hash result.
You need an integer for a draw or temporary authentication code in PHP, and it must be unpredictable. Which choice is appropriate?
Answer: Use random_int, which provides cryptographically secure random integers
random_int returns an unbiased cryptographically secure integer. For raw token bytes, random_bytes is also suitable. Observable values such as timestamps and sequences are inappropriate for authentication randomness.
With PDO, an order row and inventory count must be updated together, and both must be undone if either fails. Which implementation is appropriate?
Answer: Call beginTransaction, perform both updates, commit on success, and rollBack an active transaction on exception
Putting related updates in one transaction commits them only when all succeed. Database-specific behavior such as implicit commits for DDL still matters, so keep only operations that the target database can roll back inside the transaction.
Under load, a PDO update transaction occasionally fails because of a deadlock. What is an appropriate retry policy?
Answer: Detect only retryable errors, roll back the whole transaction, and rerun it from the beginning with bounded attempts and backoff
After a deadlock, the transaction may be aborted. Detect the database-specific retryable code and rerun the entire unit in a new transaction. Bound attempts, add backoff, and record observable logs to avoid retry storms.
PHP-FPM latency is rising, and both the listen queue and max children reached remain elevated. What should you do first?
Answer: Measure an internally restricted FPM status page, request time, memory per child, and downstream health, then tune slow work and pm.max_children within capacity
The FPM queue and max-children counter indicate worker saturation, but only raising the limit can exhaust memory or database connections. Restrict status access and evaluate request time, resource use, and downstream capacity together.
Production PHP-FPM has OPcache timestamp validation disabled. How should a deployment reliably activate new code?
Answer: Deploy an atomic release, safely reload the web FPM processes or invalidate their OPcache, and then run health checks
When OPcache timestamp validation is disabled, changing files alone can leave old bytecode active. CLI and web SAPIs may use separate caches, so deployment must explicitly refresh the target FPM cache and verify the release.
A PHP cURL call to an external payment API occupies FPM workers for a long time during provider incidents. What is required?
Answer: Set separate connection and total timeouts, then handle and record HTTP status and cURL errors
External I/O needs connection and total deadlines so workers do not wait indefinitely. Distinguish HTTP, transport, and business errors, then define observable failure handling for callers.
A PHP order API retried an external POST and created duplicate orders. What is the central prevention?
Answer: Send a unique idempotency key per business request, reuse the result for that key on the receiver, and bound retries
After a timeout, the caller may not know whether the receiver committed the operation. An idempotency key plus stored outcome makes retries converge on one business result instead of duplicating side effects.
You want CI to continuously check Composer dependencies for known security advisories. Which command is appropriate?
Answer: Run composer audit and define failure criteria and an update process for findings
composer audit checks installed or locked packages against security advisories. Findings still require a process for impact review, compatibility testing, upgrades, and time-limited exceptions.
A PHP application failed after deployment because the production container lacked a required PHP extension. How should CI prevent this?
Answer: Run composer check-platform-reqs --no-dev in the actual production image and block deployment when PHP or extension requirements fail
check-platform-reqs compares the runtime PHP version and extensions with package requirements. Running it in the production image catches missing platform dependencies before the application starts.
A PHP application has many classes, and you want fewer filesystem lookups during production autoloading. What is a safe first step?
Answer: Use composer install --no-dev --optimize-autoloader in the production build and test the artifact
Composer's optimized autoloader builds a class map from PSR rules and reduces production lookups. An authoritative class map can conflict with runtime class generation, so evaluate that stronger mode separately.
Multiple PHP-FPM child processes hold persistent connections to the same database and exhaust its connection limit. What should be reconsidered?
Answer: Calculate FPM concurrency times connections per process and design within database capacity, considering nonpersistent connections or an external pool
FPM uses multiple processes, so persistent connections are generally not one shared connection across workers. Capacity planning must include worker concurrency and per-worker connections, plus any session state retained on reuse.
A long-running PHP CLI queue worker keeps old code after deployment and its memory use grows. What is appropriate operations practice?
Answer: Release per-job state, set limits for jobs, time, and memory, and gracefully restart workers under a supervisor during deployment
Long-lived PHP processes cannot rely on request shutdown to clear all state. Combine job isolation, resource limits, signal-aware graceful shutdown, and idempotent redelivery.
During a PHP API incident, you need to correlate logs from the web request, external API call, and queue job belonging to the same user action. Which design is appropriate?
Answer: Accept or generate a correlation ID at ingress, validate it, propagate it to downstream calls and jobs, and record it in structured logs
Propagating one correlation ID across processing boundaries lets operators search distributed logs as a single action. Validate externally supplied IDs and avoid logging secrets or complete sensitive payloads.
In PHP 8.4, a public property must normalize country codes to uppercase on every assignment. Which feature fits?
Answer: Normalize in a property set hook
A property hook centralizes assignment and expresses validation or normalization as part of a typed property API.
In PHP 8.4, an order ID should be publicly readable but writable only inside the class. Which approach is appropriate?
Answer: Use asymmetric property visibility with public get and private(set)
Asymmetric visibility declares separate read and write scopes, combining convenient reading with enforced mutation control.
PHP 8.4 lazy objects are used for ORM proxies. Which initialization behavior is important?
Answer: State access such as property reads/writes, iteration, or serialization normally triggers initialization
Lazy objects defer initialization until state is needed. Understanding triggers avoids surprising database access.
A misspelled method was intended to override a parent method but became a new method. How can PHP 8.3+ detect this?
Answer: Add #[Override] so PHP verifies an actual override
#[Override] errors when no matching parent or interface method exists and also catches refactoring drift.
You need the first array element matching a predicate. Which PHP 8.4 function expresses this directly?
Answer: array_find()
array_find() returns the first value whose callback is true, or null when none matches.
User-supplied HTML must be parsed according to HTML5 rules. Which PHP 8.4 API is appropriate?
Answer: Use Dom\HTMLDocument and still sanitize the parsed result with an allowlist
The new DOM API provides standards-compliant HTML5 parsing, but parsing and XSS sanitization are separate responsibilities.
Monetary calculations must avoid floating-point error. What is appropriate when using PHP 8.4 BcMath\Number?
Answer: Construct from decimal strings and define scale and rounding as business rules
Arbitrary-precision decimal math still requires avoiding float inputs and defining scale and rounding explicitly.
SQLite-specific PDO APIs should be used with a driver-aware type. What is appropriate in PHP 8.4?
Answer: Connect with PDO::connect() and use the returned Pdo\Sqlite subclass API
Driver-specific PDO subclasses expose available capabilities in the type and reduce calls against the wrong driver.
PHP 8.5's pipe operator chains string transformations. What should code review verify?
Answer: Each stage is a callable accepting the prior value as one argument, with clear types and order
The pipe operator passes the left value sequentially to the callable on the right; it does not add parallelism or validation.
In PHP 8.5, a readonly value object needs a new instance with selected properties changed. Which feature fits?
Answer: Use clone with to specify changes during cloning
Clone with simplifies with-methods for immutable objects and creates a derived value without mutating the original.
In PHP 8.5, you want a warning when callers discard an important return value. Which attribute applies?
Answer: #[NoDiscard]
#[NoDiscard] warns when a return value is unused; an intentional discard can be made explicit with a (void) cast.
A URL used for signing requires strict normalization. What is appropriate with PHP 8.5's new URI API?
Answer: Choose a standards-specific type such as Uri\Rfc3986\Uri and handle parse failures explicitly
Use a standards-aware URI object and align component parsing and normalization between signer and verifier.
PHP 8.5 persistent cURL share handles are considered for connection reuse. What operational judgment is required?
Answer: Validate shared data, origin isolation, credentials, process lifetime, and recreation after failure
Cross-request reuse can reduce setup cost, but sharing boundaries and long-lived state must be included in capacity and failure design.
Production is upgrading from PHP 8.4 to 8.5. Which approach is safest?
Answer: Review migration and dependency requirements, test with deprecations enabled, stage rollout, and prepare rollback
Minor versions still include compatibility changes and deprecations. Production-like testing and gradual rollout limit impact.
CI should detect composer.json/lock mismatch and problematic constraints. Which command is appropriate?
Answer: composer validate --strict
Validate checks composer.json validity and lock synchronization; --strict can make warnings return a nonzero status.
You need to identify Composer dependencies blocking PHP 8.5. Which investigation is appropriate?
Answer: Use composer prohibits php 8.5 --tree to trace blocking constraints
Prohibits explains which dependency constraints block a target version, and --tree traces them to the root.
An API-key argument must not appear in exception stack traces. What PHP 8.2+ defense helps?
Answer: Mark the argument #[SensitiveParameter] and also retain log redaction controls
#[SensitiveParameter] redacts trace arguments, but cannot stop explicit application logging elsewhere, so layered controls remain necessary.
A long-running worker caches values per object but should release them when the object is destroyed. Which structure fits?
Answer: Use WeakMap so entries disappear when object keys have no other references
WeakMap keys do not keep objects alive, preventing derived cache entries from outliving their source objects.
A team assumes Fiber automatically makes blocking I/O asynchronous. Which explanation is correct?
Answer: Fiber provides cooperative suspend/resume; nonblocking I/O still needs an event loop or supporting library
Fibers can suspend an entire call stack, but scheduling and I/O multiplexing must be supplied separately.
A session cookie is used inside embedded iframes and PHP 8.5 supports Partitioned. Which prerequisite is important?
Answer: Meet browser requirements such as Secure and test partitioned-storage compatibility and authentication flows in real browsers
Partitioned cookies isolate state by top-level site, but Secure requirements, browser support, SameSite, and CSRF controls still need validation.