PHP Interview Questions for Meta

1. What is Composer, and why is it used in PHP projects?
Composer is a dependency manager for PHP. It automates package installation, versioning, and dependency management.


2. How do you initialize a Composer project?

bashCopyEditcomposer init

3. What is PSR-4 Autoloading in PHP?
It’s a standard for class autoloading using namespaces and directory structures. Composer uses it to load classes automatically.


4. How do you implement class autoloading without Composer?

spl_autoload_register(function ($class) {
include $class . '.php';
});

5. How do you store environment-specific variables securely?
By using .env files along with the vlucas/phpdotenv Composer package.


6. What is the difference between public, private, and protected in OOP?

  • public: Accessible everywhere.
  • protected: Accessible in class and subclasses.
  • private: Accessible only within the class.

7. What is Late Static Binding in PHP?
It allows static methods in parent classes to reference the child class using static:: instead of self::.


8. How do you handle JSON API requests in PHP?

$data = json_decode(file_get_contents('php://input'), true);

9. How can you generate CSRF tokens in PHP?

session_start();
$_SESSION['token'] = bin2hex(random_bytes(32));

10. How do you validate CSRF tokens?
Check if the submitted token matches $_SESSION['token'] before processing the request.


11. What is the purpose of final classes and methods in PHP?
They prevent further inheritance or method overriding, ensuring stability of base logic.


12. How do you handle CORS (Cross-Origin Resource Sharing) in PHP APIs?

header("Access-Control-Allow-Origin: *");

13. How can you log user activities efficiently?

  • Use log files (error_log()).
  • Integrate with centralized log services like ELK Stack.

14. How do you encrypt and decrypt data in PHP?
Using openssl_encrypt() and openssl_decrypt() functions.


15. What are traits and when should you use them?
Traits are used to share methods across classes without inheritance.


16. How do you handle file uploads securely?

  • Validate file types and sizes.
  • Store files outside the web root.
  • Rename uploaded files to avoid overwriting.

17. What is RESTful API, and how can you implement it in PHP?
A RESTful API uses HTTP methods (GET, POST, PUT, DELETE) to interact with resources. It can be implemented using plain PHP or frameworks like Laravel.


18. How do you handle API authentication in PHP?
Using tokens such as API keys, JWT (JSON Web Tokens), or OAuth 2.0.


19. What is JWT, and how is it used?
JSON Web Token is a compact, secure way to transmit information between parties. Used for stateless authentication.


20. How do you generate a JWT in PHP?
Use libraries like firebase/php-jwt with Composer.


21. How do you parse URLs in PHP?

$url = parse_url("https://meta.com/profile?id=123");

22. How do you cache API responses in PHP?

  • Store responses in files or in-memory solutions like Redis or Memcached.
  • Set HTTP caching headers.

23. How do you prevent SQL Injection in PHP?

  • Use prepared statements with PDO or MySQLi.
  • Avoid directly embedding user inputs in SQL queries.

24. How do you sanitize user inputs in PHP?
Using functions like filter_var(), htmlspecialchars(), and validation libraries.


25. How can you handle huge data exports efficiently?
Use output buffering and generate files in chunks to prevent memory overflow.


26. How do you validate email addresses in PHP?

filter_var($email, FILTER_VALIDATE_EMAIL);

27. How do you handle long-running scripts in PHP?

  • Use set_time_limit(0);.
  • Process data in batches.

28. How do you implement rate limiting in APIs using PHP?
Track request counts per IP in Redis or Memcached and restrict after a threshold.


29. What is the difference between yield and return?
yield returns a value without closing the function, allowing memory-efficient generators.


30. Provide an example of a generator in PHP.

function countUp() {
for ($i = 1; $i <= 5; $i++) {
yield $i;
}
}

31. How do you implement pagination in PHP APIs?
Use SQL LIMIT and OFFSET, and return metadata like total pages and current page in API responses.


32. How do you hash passwords securely in PHP?

$hash = password_hash($password, PASSWORD_BCRYPT);

33. How do you verify hashed passwords?

password_verify($inputPassword, $hash);

34. How can you detect and prevent XSS attacks?
Escape outputs using htmlspecialchars() and validate all user inputs.


35. What is the purpose of the __call() magic method?
It handles calls to undefined methods dynamically.


36. How do you read environment variables in PHP?

$env = getenv('DB_HOST');

37. How can you handle multi-language support in a PHP app?
Store language files and implement dynamic content replacement based on user selection.


38. How do you integrate social logins like Facebook/Google in PHP apps?
Use OAuth 2.0 libraries and APIs provided by the platforms.


39. What is the difference between GET and POST methods?

  • GET: Data is visible in the URL, used for data retrieval.
  • POST: Data is sent in the request body, used for data creation.

40. How do you redirect to another page in PHP?

header("Location: home.php");
exit();

41. How do you check if a file is writable?

is_writable("file.txt");

42. What is the difference between mysqli and PDO?

  • mysqli: Specific to MySQL.
  • PDO: Database-agnostic and supports multiple databases.

43. How do you prevent session hijacking in PHP?

  • Regenerate session IDs regularly.
  • Use HTTPS and HttpOnly cookies.

44. How do you manage background tasks in PHP?
Use tools like cron jobs, supervisord, or message queues like RabbitMQ.


45. How do you set cookies securely?

setcookie("user", "Meta", time()+3600, "/", "", true, true);

(The last two true values enable Secure and HttpOnly flags.)


46. How do you log API errors in PHP?
Using error_log() or integrating with third-party logging systems like Sentry.


47. How can you improve performance of a PHP web application?

  • Use caching.
  • Minimize database queries.
  • Optimize loops and array operations.
  • Use opcode caching (OPcache).

48. How do you handle invalid routes in a PHP API?
Return a proper 404 HTTP status code and a JSON error response.


49. What is the difference between synchronous and asynchronous API calls?

  • Synchronous: Waits for response before proceeding.
  • Asynchronous: Proceeds without waiting for response.

50. How do you handle file downloads in APIs?

header('Content-Disposition: attachment; filename="file.pdf"');
readfile('file.pdf');