Cherreads

Chapter 7 - PHP

1. What is PHP?

PHP is a server-side scripting language created by Rasmus Lerdorf, primarily used for web development to create dynamic and interactive websites. It is open-source, cross-platform, and easily embeds into HTML.

2. How do you redirect a page in PHP?

You use the header() function to send a raw HTTP header to the browser.

Example: header("Location: newpage.php"); exit(); (always call exit after header).

3. Difference between session_unset() and session_destroy()?

session_unset() clears variables but keeps the session alive. session_destroy() completely removes session data from the server and kills the session, requiring a new start to reuse.

4. Is PHP a case-sensitive language?

PHP is partially case-sensitive. Variables are case-sensitive (e.g., $VAR vs $var), but function names, class names, and keywords are not.

5. Difference between PHP and ASP.NET?

PHP is an open-source, cross-platform scripting language. ASP.NET is a web framework by Microsoft (primarily C#) that is compiled and often faster but traditionally Windows-centric.

6. How does PHP handle form data?

It uses superglobals: $_GET collects data from the URL (visible/insecure) and $_POST collects data from the HTTP body (invisible/secure), often used for sensitive info like passwords.

7. What is the full form of PHP?

PHP stands for "Hypertext Preprocessor." Originally, it stood for "Personal Home Page."

8. What was the old name of PHP?

The original name was "Personal Home Page" tools.

9. What are the uses of PHP?

It is used to generate dynamic page content, collect form data, manage cookies/sessions, interact with databases (CRUD operations), and control user access.

10. What is PEAR in PHP?

PEAR (PHP Extension and Application Repository) is a framework and distribution system for reusable PHP code components and libraries, managed via a command-line interface.

11. Difference between static and dynamic websites?

Static sites have fixed content (HTML/CSS) that is the same for every visitor. Dynamic sites (PHP/DB) generate content in real-time based on user actions or database data.

12. Rules for naming a PHP variable?

Variables must start with $, followed by a letter or underscore. They cannot start with a number, cannot contain spaces, and are case-sensitive.

13. How to execute a PHP script from the command line?

Open a terminal, navigate to the directory, and run php filename.php. You can also start a local server using php -S localhost:8000.

14. Most used method for hashing passwords in PHP?

password_hash() is the standard, secure method using Bcrypt. Older methods like crypt(), MD5, or SHA-1 are considered insecure and should be avoided.

15. Does JavaScript interact with PHP?

Yes, typically via AJAX. JavaScript (client-side) sends HTTP requests to PHP (server-side), and PHP processes the request and returns data (JSON/HTML) without a page reload.

16. Main types of errors in PHP?

Notices (non-critical, script runs), Warnings (critical but script runs, e.g., missing file), and Fatal Errors (critical, script stops immediately, e.g., undefined function).

17. How do you define a constant in PHP?

Use the define() function: define("NAME", "value");. Constants do not use the $ sign, are immutable, and have global scope.

18. Popular frameworks in PHP?

Laravel, Symfony, CodeIgniter, CakePHP, Yii, and Zend Framework are among the most widely used for structured development.

19. Popular Content Management Systems (CMS) in PHP?

WordPress (most popular), Joomla, Drupal, and Magento (e-commerce).

20. Purpose of break and continue statements?

break terminates the loop entirely. continue skips the current iteration and jumps immediately to the next iteration of the loop.

21. Use of count() function?

count() returns the number of elements in an array or object. It returns 0 if the variable is empty or not set.

22. Different types of loops in PHP?

PHP supports four loops: for (fixed iterations), while (condition based), do-while (executes at least once), and foreach (iterating arrays/objects).

Intermediate Level

23. Main difference between PHP 4 and PHP 5?

PHP 5 introduced a robust Object Model (OOP) with public/private/protected access, constructors, interfaces, and better XML support, whereas PHP 4 had very limited OOP capabilities.

24. Importance of Parser in PHP?

The parser converts human-readable PHP source code into machine-readable tokens/structure that the Zend Engine can execute.

25. Difference between for and foreach loop?

for is used when you know the number of iterations or need a counter. foreach is specifically designed to iterate easily over arrays and objects without managing a counter.

26. How can PHP and HTML interact?

PHP is embedded within HTML using tags. PHP executes on the server to generate dynamic HTML content, which is then sent to the client browser.

27. Main error types and differences?

Syntax/Parse errors (typos) stop execution before it starts. Fatal errors (runtime) stop execution immediately. Warnings and Notices alert the user but allow the script to finish.

28. What is inheritance in PHP?

Inheritance allows a child class to derive properties and methods from a parent class using the extends keyword, enabling code reuse.

29. Does PHP support multiple inheritance?

No, a class cannot extend multiple classes directly. However, PHP supports implementing multiple Interfaces or using Traits to achieve similar functionality.

30. What are Traits in PHP?

Traits are a mechanism for code reuse that allows you to include methods in a class without using inheritance, solving single-inheritance limitations.

31. Difference between GET and POST?

GET sends data via URL parameters (visible, limited length, cached). POST sends data in the HTTP request body (invisible, unlimited length, secure).

32. Difference between unset() and unlink()?

unset() destroys a variable in memory. unlink() deletes a physical file from the server's filesystem.

33. What does (x === y) return if x=10 and y="10"?

It returns false. The === operator checks for both value and data type. Since one is an integer and the other is a string, they are not identical.

34. What are Nullable types in PHP?

By adding a ? before a type declaration (e.g., ?int), you allow a function argument or return value to be either that specific type or null.

35. Maximum file upload size in PHP?

Default is usually 2MB or 128MB depending on version, but it is configurable via upload_max_filesize and post_max_size in the php.ini file.

36. What are PHP streams?

Streams provide a generalized way to handle file, network, and data compression operations, allowing different resources to be read/written using a common set of functions.

37. What is autoloading?

Autoloading (via spl_autoload_register) automatically loads class files when they are needed, eliminating the need to manually write include or require for every class.

38. How to prevent Cross-Site Scripting (XSS)?

Sanitize user input and escape outputs using htmlspecialchars() or htmlentities() to convert special characters into HTML entities so the browser doesn't run them as code.

39. Difference between crypt() and password_hash()?

password_hash() is the modern standard using strong algorithms (bcrypt) and auto-salting. crypt() is an older function that requires manual salt management and supports weaker algorithms.

40. How to create and use an interface?

Define with interface Name { public function method(); }. Classes use implements Name and must define all methods declared in the interface.

41. How to send an email using PHP?

Use the mail($to, $subject, $message, $headers) function. For more reliable delivery, libraries like PHPMailer are often used instead of the built-in function.

Advanced Level

42. What is dependency injection?

It is a design pattern where object dependencies are passed into a class (e.g., via constructor) rather than the class creating them, improving testability and decoupling.

43. Explain SOLID principles.

Five OOP design principles (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) intended to make software designs more understandable, flexible, and maintainable.

44. How to optimize PHP performance?

Use OPcache to store compiled bytecode, optimize database queries, use caching (Redis/Memcached) for data, and ensure latest PHP version usage.

45. What is middleware in PHP frameworks?

Middleware acts as a filter layer between a request and a response, handling tasks like authentication, logging, or CORS before the request reaches the core logic.

46. Steps to create a DB using MySQL and PHP?

Connect to the server using mysqli or PDO, check connection success, execute a CREATE DATABASE name SQL query, and close the connection.

47. Reverse string without strrev()?

Loop through the string starting from the last index (length - 1) down to 0, appending each character to a new string variable.

48. Remove duplicates from an array?

Use array_unique() to filter out duplicates, followed by array_values() to re-index the keys sequentially.

49. Check if a string is a palindrome?

Reverse the string (using strrev or a loop) and compare it to the original string. If they are identical (usually checking case-insensitively), it is a palindrome.

50. Find the second largest number in an array?

Remove duplicates with array_unique, sort the array in descending order using rsort, and access the element at index 1 ($arr[1]).

51. Check if a number is prime?

Loop from 2 up to the square root of the number. If the number is divisible by any iterator (modulus 0), it is not prime.

52. Recursive factorial function?

Return 1 if the number is <= 1. Otherwise, return the number multiplied by the function calling itself with number - 1.

53. Sort array without sort()?

Implement a bubble sort: use nested loops to compare adjacent elements and swap them if they are in the wrong order until the array is sorted.

54. Merge two sorted arrays?

Use array_merge($arr1, $arr2). Note: This merges them but doesn't strictly maintain sort order unless you re-sort the result or implement a specific merge algorithm.

55. Generate Fibonacci series?

Initialize an array with [0, 1]. Loop starting from index 2, setting the current element as the sum of the previous two ($arr[$i-1] + $arr[$i-2]).

56. Find most frequent element?

Use array_count_values() to get frequency counts, sort descending with arsort(), and grab the first key using array_key_first().

57. Reduce memory usage in PHP?

Unset large variables when done, use Generators (yield) for large loops, process data in chunks rather than loading all at once, and enable OPcache.

58. What is lazy loading?

A pattern where objects or resources (like database connections) are only initialized/loaded when they are actually accessed, saving memory and startup time.

59. What is opcode cache?

It stores precompiled script bytecode in shared memory. This allows PHP to execute code without parsing/compiling it on every request, drastically boosting speed.

60. What are PHP generators?

Functions that use the yield keyword to return data one item at a time during iteration, rather than building and returning a massive array in memory.

61. What is CSRF and how to prevent it?

Cross-Site Request Forgery forces users to perform unwanted actions. Prevent it by including a unique, secret CSRF token in forms and verifying it on submission.

62. What is Type Hinting?

Specifying the expected data type (e.g., int, string, Class) for function arguments and return values to enforce type safety and reduce errors.

63. What is middleware in Laravel?

A mechanism to filter HTTP requests entering your application. For example, auth middleware verifies if a user is logged in before allowing access to a route.

64. Difference between Laravel and Symfony?

Laravel is opinionated, developer-friendly, and great for rapid dev. Symfony is more modular, strict, config-heavy, and often used for large-scale enterprise apps.

65. Explain the Repository Pattern.

It creates an abstraction layer between the application logic and the data layer (database). This decouples code, making it easier to switch data sources or test logic.

Here are the concise notes for your additional PHP interview questions.

1. What is PHP?

PHP (Hypertext Preprocessor) is a popular, open-source server-side scripting language designed for web development. It is used to generate dynamic content, interact with databases, and is easily embedded directly into HTML code.

2. What is the difference between echo and print in PHP?

echo has no return value, can take multiple parameters, and is marginally faster. print returns a value of 1 (so it can be used in expressions) and accepts only a single argument.

3. What are the different types of variables in PHP?

PHP has three main variable categories: Scalar (Integer, Float, String, Boolean), Compound (Array, Object), and Special (NULL, Resource).

4. What are superglobals in PHP?

Superglobals are built-in variables that are available in all scopes throughout a script. Examples include $_GET, $_POST, $_SESSION, $_COOKIE, and $_SERVER.

5. What is the difference between == and === in PHP?

The == operator checks for value equality, performing type conversion if necessary (e.g., 1 == "1" is true). The === operator checks for identity, requiring both the value and the data type to match (e.g., 1 === "1" is false).

6. What are sessions and cookies in PHP?

Sessions store user data on the server side and track the user via a session ID. Cookies store data on the client's browser as text files and are sent to the server with every HTTP request.

7. What are the advantages of using PHP?

PHP is open-source and free, platform-independent (runs on Windows, Linux, Mac), has a massive support community, and integrates seamlessly with major databases like MySQL and HTML.

8. How does PHP handle error handling?

PHP handles errors using conditional statements (like die()), custom error handling functions (set_error_handler), and object-oriented exception handling using try, catch, and throw blocks.

9. What is a PHP function?

A function is a block of reusable code designed to perform a specific task. It can accept input parameters, execute logic, and return a value to the part of the script that called it.

10. What is the difference between include() and require() in PHP?

include() generates a warning if the file is not found, allowing the script to continue execution. require() generates a fatal error if the file is missing, stopping the script execution immediately.

Basic Level

1. What is PHP, and what does it stand for?

PHP stands for Hypertext Preprocessor. It is a server-side scripting language used to develop dynamic websites and web applications that interact with databases.

2. What is the difference between PHP and HTML?

HTML is a client-side markup language used to structure the design of a webpage. PHP is a server-side scripting language used to handle logic, data processing, and database interaction.

3. What is the difference between echo and print in PHP?

echo has no return value and can take multiple parameters (though rarely used). print returns a value of 1, making it usable in expressions, but it is marginally slower than echo.

4. How do you define a variable in PHP?

Variables in PHP start with a $ sign followed by the name of the variable.

Example: $count = 10; or $message = "Hello";.

5. What are PHP data types? Can you name a few?

Data types specify the type of data a variable holds. Common types include String, Integer, Float, Boolean, Array, Object, NULL, and Resource.

6. How do you declare a constant in PHP?

Constants are declared using define() or the const keyword.

Example: define("SITE_URL", "www.example.com"); or const PI = 3.14;.

7. What is the purpose of the isset() function in PHP?

isset() checks if a variable is declared and is strictly not NULL. It returns true if the variable exists and has a value.

8. What is the use of the empty() function in PHP?

empty() checks if a variable is empty. It returns true for "", 0, NULL, false, or an empty array.

9. What are the differences between == and === in PHP?

== (Equal) checks only for value equality (performs type coercion). === (Identical) checks for both value equality and data type (e.g., 5 === "5" is false).

10. How do you create an array in PHP? Provide an example.

Arrays are created using the array() function or short syntax [].

Example: $colors = ["Red", "Green", "Blue"];.

11. How do you access elements in an associative array?

You access elements using their specific key strings.

Example: $age['Peter'] retrieves the value associated with the key "Peter".

12. What are the different types of arrays in PHP?

Indexed Arrays (numeric keys), Associative Arrays (named keys), and Multidimensional Arrays (arrays containing one or more arrays).

13. What is the difference between include() and require() in PHP?

include() throws a Warning if the file is missing, and the script continues. require() throws a Fatal Error, stopping the script execution immediately.

14. What is the purpose of include_once() and require_once()?

These functions behave exactly like their counterparts but check if the file has already been included. If so, they do not include it again, preventing function re-declaration errors.

15. How do you create a simple form in PHP and collect data from it?

Create an HTML form with method="POST". In PHP, access the input values using the $_POST['input_name'] superglobal array.

16. What is the use of the $_GET superglobal in PHP?

It collects form data sent via the URL parameters (query string). It is visible in the browser address bar and is not secure for sensitive data.

17. What is the use of the $_POST superglobal in PHP?

It collects form data sent via the HTTP POST method. Data is sent in the request body, is not visible in the URL, and is suitable for sensitive information.

18. What are PHP sessions, and how do they work?

Sessions store user information on the server to be used across multiple pages (e.g., login status). They work by creating a unique Session ID for each visitor.

19. What is the difference between cookies and sessions in PHP?

Cookies are stored on the client's computer (browser) and have size limits. Sessions are stored on the server and are generally more secure and can hold more data.

20. How do you redirect a user to another page in PHP?

Use the header() function.

Example: header("Location: dashboard.php"); exit();.

21. What is a PHP function, and how do you define one?

A function is a block of code written to perform a specific task.

Syntax: function functionName() { /* code */ }.

22. How do you handle errors in PHP?

Basic handling uses die() or if checks. Advanced handling uses try, catch blocks with Exceptions, or custom error handlers using set_error_handler().

23. What are some common PHP functions for string manipulation?

strlen() (length), str_replace() (replace text), strpos() (find position), explode() (split string to array), strtolower() (to lowercase).

24. What is the difference between substr() and str_replace() in PHP?

substr() extracts a portion of a string based on position. str_replace() searches for specific text within a string and replaces it with new text.

25. What is a PHP constructor, and how is it used?

A constructor is a special method (__construct()) in a class that is automatically called when an object is created. It is used to initialize object properties.

26. What is the purpose of the date() function in PHP?

It formats a local date and time.

Example: echo date("Y-m-d"); prints the current date like "2023-10-25".

27. What are the different loop structures available in PHP?

for (specific iterations), while (condition is true), do-while (executes at least once), and foreach (iterates over arrays).

28. What is the difference between session_start() and session_destroy()?

session_start() initializes or resumes a session. session_destroy() deletes all session data and ends the session.

29. How do you create a simple database connection in PHP using MySQL?

Using MySQLi: $conn = new mysqli($host, $user, $pass, $db);.

Using PDO: $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);.

30. What is the purpose of mysql_query() in PHP?

It was used to execute SQL queries in older PHP versions. It is now deprecated and removed; mysqli_query or PDO methods should be used instead.

31. What is the mysqli extension in PHP?

MySQLi ("i" stands for improved) is an extension used to access MySQL databases. It supports both object-oriented and procedural interfaces and prepared statements.

32. How do you fetch data from a MySQL database in PHP?

After executing a query, use mysqli_fetch_assoc($result) or $stmt->fetch(PDO::FETCH_ASSOC) to retrieve rows as associative arrays.

33. How do you sanitize user input in PHP to prevent SQL injection?

Always use Prepared Statements (with PDO or MySQLi) which separate SQL logic from data. Alternatively, use functions like mysqli_real_escape_string().

34. What are regular expressions in PHP? How do you use them?

Regex is a sequence of characters defining a search pattern. PHP uses functions starting with preg_ (e.g., preg_match, preg_replace) to work with them.

35. What is the use of the $_FILES superglobal in PHP?

It is a multidimensional array containing information about files uploaded via a form (name, type, tmp_name, error, size).

36. How do you manage file uploads in PHP?

Ensure the form has enctype="multipart/form-data". In PHP, use move_uploaded_file($_FILES['file']['tmp_name'], $targetPath) to save the file.

37. What are magic methods in PHP? Give an example.

Magic methods start with __ and allow you to define how objects behave in specific events. Examples: __construct, __destruct, __toString, __get.

Intermediate Level

38. What are namespaces in PHP, and how do they help in avoiding name conflicts?

Namespaces encapsulate items (classes, functions) to prevent naming collisions between your code and internal PHP classes or third-party libraries.

Syntax: namespace MyProject\Utils;.

39. Explain the concept of PHP OOP (Object-Oriented Programming).

OOP organizes code into Objects (instances) and Classes (blueprints), focusing on modularity and reusability rather than procedural logic.

40. What are the basic principles of Object-Oriented Programming in PHP?

Encapsulation (hiding data), Inheritance (class hierarchy), Polymorphism (multiple forms/interfaces), and Abstraction (hiding complexity).

41. What is the difference between public, private, and protected visibility in PHP?

Public: Accessible from anywhere. Private: Accessible only within the defining class. Protected: Accessible within the class and its child (inherited) classes.

42. What is an interface in PHP, and how is it different from an abstract class?

An interface defines what methods a class must implement (without code). An abstract class can provide some implementation details (code) alongside abstract methods.

43. What is the difference between static and non-static methods in PHP?

Static methods belong to the class and are called without creating an object (Class::method()). Non-static methods belong to an object instance ($obj->method()).

44. How do you handle exceptions in PHP? What is try-catch block?

Wrap risky code in a try block. If an error occurs, an Exception is thrown and caught by the catch block, allowing the script to handle the error gracefully.

45. What is dependency injection in PHP?

It is a technique where dependencies (objects a class needs) are passed into the class (usually via constructor) rather than the class creating them itself.

46. What is a constructor injection in PHP?

A specific type of dependency injection where the required dependencies are passed as arguments to the class's __construct() method.

47. How does the __autoload() function work in PHP? (Or its modern alternative)

It allows classes to be loaded automatically when needed. The modern approach is spl_autoload_register(), which registers functions to load class files dynamically.

48. Explain traits in PHP and how they are used.

Traits allow code reuse in single-inheritance languages. They define methods that can be used in multiple classes using the use TraitName; statement.

49. What are the advantages of using prepared statements in PHP?

They pre-compile the SQL statement on the database server, which improves performance for repeated queries and, most importantly, completely prevents SQL Injection attacks.

50. How do you connect to a database using PDO (PHP Data Objects)?

$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);. PDO allows you to switch databases easily because it supports multiple database drivers.

51. What is the difference between mysqli and PDO in PHP?

MySQLi works only with MySQL databases. PDO is database-agnostic and supports 12+ different database systems, making the application more flexible.

52. What is SQL injection, and how can you prevent it in PHP?

It is an attack where malicious SQL code is inserted into input fields. Prevent it by using Prepared Statements (parameterized queries).

53. How does PHP error handling work, and how do you configure error reporting in PHP?

Error reporting levels are set in php.ini or using error_reporting(E_ALL); and ini_set('display_errors', 1); during development to see issues on screen.

54. What is the Symfony framework, and how does it compare with Laravel?

Symfony is a high-performance, component-based framework known for strict standards. Laravel is built on top of Symfony components but focuses more on developer speed and ease of use.

55. How do you perform unit testing in PHP?

Use PHPUnit, the standard testing framework. It allows you to write test classes that assert whether individual functions or methods produce expected results.

56. What is composer in PHP, and how does it manage dependencies?

Composer is a dependency manager for PHP. It uses a composer.json file to install and update libraries and manages autoloading of classes.

57. What are the design patterns you have used in PHP?

Common patterns include Singleton (DB connection), Factory (object creation), Observer (event handling), and Strategy (switching algorithms).

58. What is the MVC (Model-View-Controller) architecture in PHP?

It separates the app into: Model (Database/Data), View (User Interface/HTML), and Controller (Business Logic handling requests).

59. What are closure functions in PHP?

Closures are anonymous functions (functions without a name) that can capture variables from the parent scope using the use keyword.

60. What is JSON encoding/decoding in PHP?

json_encode($data) converts a PHP array/object to a JSON string. json_decode($jsonString) converts a JSON string back into a PHP object or array.

61. What is Laravel? Can you explain some of its core features?

Laravel is a popular PHP framework. Features include Eloquent ORM (database interaction), Blade (templating), Artisan (CLI), and built-in Authentication.

62. What is middleware in PHP (Laravel/Slim)?

Middleware provides a mechanism for filtering HTTP requests entering your application (e.g., checking if a user is logged in) before they reach the controller.

63. How does routing work in PHP frameworks?

Routing maps a URL (e.g., /user/profile) to a specific controller method or closure function that handles the request and returns a response.

64. How do you implement user authentication in PHP?

Verify the user's input password against the stored hashed password using password_verify(). If valid, start a session using session_start() to log them in.

65. What are the security best practices you follow while developing with PHP?

Validate inputs, sanitize outputs (XSS prevention), use prepared statements (SQLi prevention), use HTTPS, and implement CSRF tokens in forms.

66. How do you implement pagination in PHP?

Use SQL LIMIT and OFFSET. Calculate the offset based on the current page number: OFFSET = (page_number - 1) * items_per_page.

67. What is Redis and how do you use it in PHP applications?

Redis is an in-memory data store used for caching and message queuing. In PHP, it is used to store frequently accessed data to reduce database load.

68. What are WebSockets and how can they be implemented in PHP?

WebSockets allow real-time, bi-directional communication. In PHP, libraries like Ratchet or extensions like Swoole are used to create WebSocket servers.

69. What is RESTful API architecture?

It is an architectural style for APIs using standard HTTP methods (GET, POST, PUT, DELETE) and stateless communication, typically exchanging data in JSON format.

70. Explain Cross-Origin Resource Sharing (CORS).

CORS is a security feature that restricts web pages from making requests to a different domain. In PHP, you allow it by setting headers like Access-Control-Allow-Origin.

Experienced Level

71. How do you optimize PHP applications for better performance?

Enable OPcache, use object caching (Redis), optimize database indexing, minimize I/O operations, and use a CDN for static assets.

72. What is PHP-FPM and how does it improve performance?

PHP-FPM (FastCGI Process Manager) is an alternative PHP implementation that handles high loads better by maintaining a pool of worker processes to handle requests.

73. What is PHP OPCache?

OPCache improves performance by storing precompiled script bytecode in shared memory, removing the need for PHP to load and parse scripts on every request.

74. How do you monitor and debug a PHP application in production?

Use tools like New Relic or Datadog for monitoring, and check server error logs. For debugging, Xdebug is standard (mostly dev), while logging libraries like Monolog are used in production.

75. How does Garbage Collection work in PHP?

PHP uses reference counting. When a variable's reference count drops to zero, memory is freed. The Garbage Collector (gc_collect_cycles) cleans up complex cyclic references.

76. How do you implement multi-tenancy in a PHP application?

Approaches include: separate databases for each tenant, separate schemas, or a single database with a tenant_id column in every table to isolate data.

77. What is Docker, and how would you use it for PHP?

Docker containerizes the application. You create a Dockerfile to define the PHP environment (OS, extensions) ensuring consistency between development and production.

78. Explain event-driven programming in PHP.

It involves an event loop that listens for events (like I/O) and triggers callbacks, allowing non-blocking asynchronous execution (e.g., using ReactPHP or Swoole).

79. How do you implement microservices architecture in PHP?

Break the monolithic app into small, independent services (e.g., Auth, Billing) that communicate via REST APIs or message brokers like RabbitMQ.

80. Explain the SOLID principles of OOP.

Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion. These guidelines ensure scalable and maintainable code.

81. How do you ensure the security of a PHP application against attacks?

Use CSP headers for XSS, Prepared Statements for SQLi, CSRF tokens for form submission, and Rate Limiting to prevent brute force attacks.

82. What is the Singleton pattern, and when would you use it?

A design pattern ensuring a class has only one instance globally. Commonly used for Database Connections or Configuration handlers.

83. How do you perform load balancing for PHP applications?

Use a load balancer (Nginx, HAProxy, AWS ELB) to distribute incoming traffic across multiple PHP application servers to prevent overload.

84. What is the PSR (PHP Standards Recommendations)?

PSR is a set of standards (e.g., PSR-4 for autoloading, PSR-12 for coding style) that ensures interoperability and code consistency across the PHP ecosystem.

85. How do you implement OAuth authentication in PHP?

Use a library (like Laravel Socialite or League/OAuth2-Client) to handle the handshake, token exchange, and user retrieval from providers like Google or Facebook.

86. Explain the Observer design pattern in PHP.

It defines a one-to-many dependency. When the "Subject" object changes state, all attached "Observer" objects are notified and updated automatically.

87. How do you implement job queues and background processing?

Offload time-consuming tasks (sending emails, video processing) to a queue (Redis/RabbitMQ) and use a worker script to process them asynchronously.

88. How do you handle large file uploads (>2GB) in PHP?

Adjust upload_max_filesize and post_max_size in php.ini. For very large files, implement chunked uploads via JavaScript and merge chunks on the server.

89. What are PHP 7/8 new features?

PHP 7 brought speed and type hints. PHP 8 introduced JIT Compiler, Union Types, Match Expressions, Attributes, and Constructor Property Promotion.

90. How do you use Varnish or Nginx as a reverse proxy?

Place them in front of the PHP server to cache static content and full HTTP responses, serving requests directly from memory without hitting PHP.

91. What are the pros and cons of using an ORM?

Pros: Faster development, security, database abstraction. Cons: Can be slower than raw SQL, and complex queries can be difficult to optimize.

92. How do you manage version control for PHP code?

Use Git. Follow branching strategies like Git Flow (feature branches, develop, master) and use GitHub/GitLab for code hosting and reviews.

93. What is PHP Swoole?

Swoole is a coroutine-based asynchronous networking engine for PHP. It allows PHP to build high-performance, concurrent servers (like Go/Node.js) without Nginx.

94. How do you perform asynchronous processing in PHP?

Traditionally via Job Queues. Modern approaches use Fibers (PHP 8.1), Swoole, or ReactPHP for non-blocking I/O operations.

95. What is JWT (JSON Web Token)?

A compact, URL-safe means of representing claims to be transferred between two parties. In PHP, it is used for stateless API authentication.

96. How would you use GraphQL in a PHP application?

GraphQL allows clients to request exactly the data they need. In PHP, you define a Schema and Resolvers (using libraries like webonyx/graphql-php) to fetch data.

97. What is the Service Container?

A tool for managing class dependencies and performing dependency injection. It binds interfaces to concrete classes, allowing automatic resolution of objects.

98. How do you ensure backward compatibility when upgrading PHP?

Check the migration guides for Deprecated features, run the test suite (PHPUnit), use tools like Rector to automate code upgrades, and use Polyfills for missing functions.

More Chapters