PHP Backend Development Comprehensive Quiz & Projects
30 questions on PHP Backend Development Tutorial.
Question 1: What does PSR-12 define in the modern PHP ecosystem?
- A. Rules for secure database connection handling in PDO.
- B. Standard coding style guidelines to ensure consistent, readable code. β (correct answer)
- C. A standard for autoloading classes using composer namespaces.
- D. Core security specifications for preventing XSS in template engines.
Explanation: PSR-12 is a PHP Standard Recommendation (PSR) that outlines style rules for formatting PHP code, succeeding PSR-2.
Question 2: Which pattern does Laravel's Service Container primarily implement to resolve class dependencies?
- A. Singleton pattern using static class accessors.
- B. Dependency Injection via constructor or setter parameters. β (correct answer)
- C. Active Record pattern for database integration.
- D. Factory Method pattern with manual config mappings.
Explanation: The Service Container is a powerful tool for managing class dependencies and performing dependency injection automatically.
Question 3: Why should developers use PDO transactions when executing multiple dependent SQL queries?
- A. Transactions automatically index database columns to increase select speed.
- B. Transactions ensure database connection persistence across requests.
- C. Transactions guarantee atomicity, rolling back all queries if one fails to preserve data integrity. β (correct answer)
- D. Transactions compress the SQL payload to reduce network traffic.
Explanation: Transactions wrap multiple statements in an all-or-nothing wrapper (Atomicity), preventing partial database updates.
Question 4: To mitigate Session Hijacking in PHP, what is the best practice after a user authenticates?
- A. Destroy the current session and switch entirely to basic authentication headers.
- B. Regenerate the session ID using session_regenerate_id(true) to invalidate the old ID. β (correct answer)
- C. Encrypt all session files on the server using AES-256.
- D. Store the session ID in a global JavaScript variable for easy request tracking.
Explanation: Regenerating the session ID invalidates the old ID, rendering it useless to an attacker who may have sniffed it before login.
Question 5: In PHP 8, how does throwing an Uncaught Error differ from an Exception?
- A. Errors cannot be caught using try-catch blocks under any circumstances.
- B. Exceptions represent critical engine errors, while Errors represent logical flaws.
- C. Both implement Throwable and can be caught, but Errors represent internal engine failures like type errors or division by zero. β (correct answer)
- D. Exceptions terminate script execution immediately, while Errors allow fallback recovery automatically.
Explanation: In PHP 7+, both Error and Exception implement the Throwable interface, allowing engine level fatal errors to be caught gracefully.
Question 6: Which superglobal array is populated when reading query parameters from a URL (e.g. ?id=5)?
- A. $_POST
- B. $_GET β (correct answer)
- C. $_SESSION
- D. $_SERVER
Explanation: The $_GET superglobal holds key-value pairs parsed from the URL's query parameters.
Question 7: What is the primary benefit of using namespaces in a PHP application?
- A. It speeds up file reading times of the compiler.
- B. It permits classes with identical names to exist in separate directories/contexts without causing naming collisions. β (correct answer)
- C. It encrypts file content in memory.
- D. It registers classes to the MySQL database.
Explanation: Namespaces organize classes into virtual packages to prevent naming conflicts.
Question 8: What is the function of Composer in a modern PHP project?
- A. It hosts the web application locally.
- B. It is a dependency manager that handles installing and updating third-party libraries. β (correct answer)
- C. It compiles PHP script files into machine binary.
- D. It acts as a database query optimizer.
Explanation: Composer automates the tracking, downloading, and autoloading of external libraries.
Question 9: How does Composer's PSR-4 autoloader resolve class files?
- A. By querying a MySQL database mappings table.
- B. By mapping namespaces directly to file system directory structures. β (correct answer)
- C. By loading all files in the project memory at startup.
- D. By looking up classes in remote web servers.
Explanation: PSR-4 matches class names/namespaces to physical directory paths for dynamic loading.
Question 10: What is the purpose of the declare(strict_types=1) directive in PHP?
- A. It disables dynamic array resizing.
- B. It forces scalar type declarations (int, string, bool) to be strictly matched at runtime, throwing type errors on mismatch. β (correct answer)
- C. It restricts database connection queries to read-only.
- D. It prevents the use of global variables completely.
Explanation: strict_types ensures variables match defined types precisely instead of being coerced automatically.
Question 11: Which PHP function is best suited to validate and sanitize email input strings?
- A. htmlspecialchars()
- B. filter_var() with validation filters β (correct answer)
- C. md5()
- D. strip_tags()
Explanation: filter_var() provides dedicated filters like FILTER_VALIDATE_EMAIL to verify input formats securely.
Question 12: How do you specify a class constructor in PHP?
- A. function constructor()
- B. function __construct() β (correct answer)
- C. class MyClass()
- D. public MyClass()
Explanation: The magic method __construct() is called automatically when an object is instantiated.
Question 13: What does it mean if a property is declared 'protected' in a class?
- A. It is accessible only from inside the defining class.
- B. It is accessible only from inside the defining class and its subclasses (child classes). β (correct answer)
- C. It is accessible globally from any file.
- D. It is encrypted in the MySQL database.
Explanation: Protected visibility restricts access to the class itself and any class that extends it.
Question 14: What does the 'static' keyword do when applied to a class method?
- A. It prevents the class from being extended by child classes.
- B. It allows the method to be accessed directly on the class without instantiating it as an object. β (correct answer)
- C. It locks the class properties to read-only.
- D. It runs the method automatically in the background.
Explanation: Static methods belong to the class blueprint itself, not individual object instances.
Question 15: What is the difference between an Interface and an Abstract Class in PHP?
- A. Interfaces can contain implementation code, while Abstract Classes cannot.
- B. Interfaces only define signatures (no body), while Abstract Classes can contain both defined signatures and concrete implemented methods. β (correct answer)
- C. Abstract classes cannot have constructors.
- D. Interfaces support private methods only.
Explanation: Abstract classes act as partial blueprints with shared code. Interfaces define pure behavior contracts.
Question 16: In modern PHP, what does the null coalescing operator (??) do?
- A. Compares two floats for equivalence.
- B. Returns the left-hand operand if it exists and is not null; otherwise, it returns the right-hand operand. β (correct answer)
- C. Divides a number and yields the remainder.
- D. Checks if a class inherits from a target interface.
Explanation: The ?? operator is a shorthand way to check if a value is set and fallback to a default value.
Question 17: Why is the bcrypt algorithm preferred over MD5 for cryptographic password hashing?
- A. bcrypt yields a shorter string, saving DB space.
- B. MD5 is computationally expensive compared to bcrypt.
- C. MD5 is fast and prone to dictionary/brute-force attacks, while bcrypt is computationally slow and includes salts. β (correct answer)
- D. MD5 is not supported on Linux systems.
Explanation: bcrypt uses a cost factor to slow down hashes, making brute-force attempts impractical.
Question 18: Which header function call redirects a user to a different URL?
- A. header('Redirect: /page')
- B. header('Location: /page') β (correct answer)
- C. header('URL: /page')
- D. header('HTTP/1.1 302 /page')
Explanation: header('Location: ...') sends a HTTP redirect header back to the browser.
Question 19: How does using htmlspecialchars() protect a PHP application from Cross-Site Scripting (XSS)?
- A. It encrypts input strings using AES-256.
- B. It converts HTML special characters like '<' and '>' to their safe HTML entities, preventing script injection. β (correct answer)
- C. It blocks SQL command patterns from running.
- D. It restricts access to administrative files.
Explanation: By encoding characters like '<' to '<', browsers render them as text rather than executing them as script tags.
Question 20: Which PHP OOP keyword is used to prevent a class from being extended by child classes?
- A. abstract
- B. final β (correct answer)
- C. interface
- D. private
Explanation: Defining a final class final MyClass prevents subclasses from inheriting or overriding its methods.
Question 21: What is the primary role of an autoloader in PHP?
- A. Automatically uploading files to an FTP server on save.
- B. Loading PHP class files dynamically on demand when the class is referenced in code, avoiding manual require statements. β (correct answer)
- C. Initializing database connections on page load.
- D. Running scheduled background cron jobs.
Explanation: Autoloaders register a callback that parses class names and loads their files when first instantiated.
Question 22: Which PDO method should you call to prevent SQL injection when parsing dynamic user input?
- A. $pdo->query()
- B. $pdo->prepare() followed by $stmt->execute() β (correct answer)
- C. $pdo->exec()
- D. $pdo->quote()
Explanation: Prepared statements compile query plans first, ensuring input parameters are treated strictly as data variables, not code.
Question 23: In MVC architecture, what is the role of the Controller?
- A. Querying database tables and structures.
- B. Receiving HTTP requests, executing business logic, and returning the response (often rendering a View). β (correct answer)
- C. Styling page layouts and graphics.
- D. Directing server caching operations.
Explanation: The controller acts as the traffic cop, processing user input, calling models, and preparing views.
Question 24: What are PHP Traits?
- A. Special variables for tracking system state.
- B. A mechanism for code reuse in single inheritance languages, allowing a class to import methods from multiple traits. β (correct answer)
- C. Methods designed to optimize database writes.
- D. Interfaces that support concrete property values.
Explanation: Traits enable classes to share methods without using complex multiple-inheritance hierarchies.
Question 25: What is the difference between session_start() and a cookie?
- A. Session variables are stored on the server, while cookies are stored on the client browser. β (correct answer)
- B. Cookies are encrypted, while sessions are stored in plain text on the network.
- C. Sessions expire instantly, while cookies never expire.
- D. There is no difference; they are identical.
Explanation: Sessions save state on the server, sending a session ID cookie to the browser to identify requests.
Question 26: Which function checks if a variable is declared and is not null?
- A. empty()
- B. isset() β (correct answer)
- C. is_null()
- D. defined()
Explanation: isset() returns true if the variable exists and does not hold a null value.
Question 27: What is a PHP generator function?
- A. A function that generates random integers.
- B. A function that yields values dynamically using the 'yield' keyword, allowing iteration over datasets without loading them entirely in memory. β (correct answer)
- C. A script that writes boilerplate OOP code files.
- D. A tool that generates SQL migration schema files.
Explanation: Generators provide memory-efficient iteration by yielding items one at a time on demand.
Question 28: What happens if you include a file using require instead of include?
- A. include stops the script on failure, while require only outputs a warning.
- B. require terminates execution with a fatal error on failure, while include outputs a warning and continues. β (correct answer)
- C. require is faster and uses less memory.
- D. require runs only on Unix-based servers.
Explanation: require is for essential dependencies; include is for optional page components.
Question 29: What does PSR-4 define?
- A. Rules for caching database queries.
- B. Coding style guide patterns.
- C. Standard autoloader namespace-to-file path mapping specifications. β (correct answer)
- D. HTTP client request standards.
Explanation: PSR-4 defines how namespaces map to project folders, standardizing automated class resolutions.
Question 30: What is the difference between print and echo in PHP?
- A. echo can take multiple arguments and has no return value, while print takes one argument and returns 1. β (correct answer)
- B. print is faster than echo.
- C. echo works only on strings, while print works only on arrays.
- D. print is an OOP method, while echo is a function.
Explanation: echo is a language construct that accepts list arguments; print behaves like a function returning 1.