Skip to main content
Interview Prep

PHP Interview Questions 2026: Freshers to 10 Years, PHP 8, Laravel, Security and Database Rounds

PHP interview guide: round pattern, PHP 8 language features, OOP, sessions and cookies, PDO and SQL injection, Laravel and Eloquent, performance, security and coding problems, with expected answers.

Published 40 min read
Share

How to use this guide

This guide covers PHP interviews from the language basics to production and security. Each answer should be explained in your own words, with the reason behind it. Security questions are common in PHP rounds, so give those sections extra time.

The answers follow the PHP documentation for PHP 8 and later, and common Laravel practice. Check the version your target company uses before you answer version-specific questions.

What the interview pattern usually looks like

RoundWhat is testedTypical length
ScreeningPHP basics, arrays, strings, a short query30 minutes
TechnicalOOP, sessions, PDO, security, HTTP45 to 60 minutes
CodingArray problems, string functions, small class design45 minutes
FrameworkLaravel, Eloquent, routing, middleware, queues45 minutes
Project and managerYour work, teamwork, ownership30 to 45 minutes

Agencies and product companies ask a lot about Laravel and database work. Enterprise companies often test security and legacy code handling.

Level 1: PHP basics

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

== compares values after type conversion. === compares values and types. Use === by default. Known traps: "0" == false is true, and 0 == "a" was true before PHP 8, and is false in PHP 8 and later.

Q2. What is the difference between echo, print, print_r and var_dump?

echo outputs one or more strings. print outputs one string and returns 1. print_r gives a readable form of arrays and objects. var_dump also shows types and sizes, which is useful for debugging.

Q3. What is the difference between single and double quotes?

Double quotes interpolate variables, such as "Hello $name". Single quotes do not, and they are slightly faster for plain text.

Q4. What is the difference between include, require, include_once and require_once?

include gives a warning and continues if the file is missing. require stops with a fatal error. The _once versions include a file only once. Use require_once for core files.

Q5. How do you read a value from an array that might not exist?

Use the null coalescing operator: $name = $_GET['name'] ?? 'guest';. It avoids a notice and reads cleanly.

Q6. What is the difference between isset and empty?

isset checks that a variable exists and is not null. empty is true for null, false, zero, an empty string and an empty array. Use isset when zero or empty strings are valid values.

Q7. What are the common array functions you should know?

array_map, array_filter, array_reduce, array_column, array_unique, array_merge, array_keys, in_array with the strict flag, and usort for custom sorting.

Level 2: PHP 8 and OOP

Q8. What are the main additions in PHP 8?

Named arguments, union types, the match expression, the nullsafe operator ?->, constructor property promotion, attributes, str_contains and related string functions, and the JIT compiler. Enums arrived in PHP 8.1 and readonly properties in 8.1.

enum Status: string {
    case Active = 'active';
    case Blocked = 'blocked';
}

function label(Status $status): string {
    return match ($status) {
        Status::Active => 'Active user',
        Status::Blocked => 'Blocked user',
    };
}

Q9. What is the difference between an interface and an abstract class?

An interface defines a contract with method signatures and no state. A class can implement many interfaces. An abstract class can hold shared code and state, and a class extends only one. Use an interface for a capability, such as Countable, and an abstract class for shared behaviour.

Q10. What are traits?

A way to reuse methods in several classes without inheritance. Use them for small shared behaviour, such as timestamps. Avoid large traits that hide dependencies.

Q11. What is autoloading, and how does Composer help?

PHP loads a class file when the class is first used. Composer generates an autoloader based on the PSR-4 namespace rules, so App\Models\User maps to src/Models/User.php.

Q12. What is dependency injection?

Passing a class's dependencies in through its constructor, instead of creating them inside. It makes code easier to test by swapping a fake for a real service.

Q13. What is the difference between public, protected and private?

public is visible everywhere. protected is visible to the class and its subclasses. private is visible only inside the class that declares it.

Level 3: Sessions, cookies and HTTP

Q14. How do PHP sessions work?

The server creates a session ID, stores session data on the server, and sends the ID to the browser in a cookie named PHPSESSID by default. Each request sends the cookie back, and PHP loads the matching data.

Q15. Why are sessions secure, and what must you still set?

The data stays on the server, but the session ID is a credential. Set cookies with HttpOnly, Secure and SameSite. Regenerate the ID after login with session_regenerate_id(true), to prevent session fixation.

Q16. What is the difference between GET and POST, and when do you use each?

GET reads data and should not change state. Its parameters appear in the URL and logs. POST sends data for a change, such as creating a record, and keeps it out of the URL. Use PUT, PATCH and DELETE for API resource changes.

Q17. How do you read request data safely?

Use $_GET, $_POST and $_FILES only after validation. Trim and check type and length. In a framework, use the request object and validation rules.

Q18. What is the difference between header() redirects and output?

Headers must be sent before any output. Otherwise PHP gives a "headers already sent" warning. Call header('Location: ...') then exit, and keep output buffering in mind for templates.

Level 4: Databases with PDO

Q19. What is PDO, and why use it over the old mysql_* functions?

PDO is the PHP Data Objects layer. It supports many database drivers through one API and supports prepared statements. The old mysql_* functions were removed in PHP 7.

Q20. Show a safe query with user input.

$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$stmt = $pdo->prepare('SELECT id, name FROM users WHERE email = :email');
$stmt->execute([':email' => $email]);
$user = $stmt->fetch();

Q21. What is the difference between prepare and query in PDO?

query runs a statement directly. prepare separates the SQL from the data, and execute sends the values separately, which prevents SQL injection.

Q22. What is a transaction, and how do you use one in PDO?

A group of statements that succeed or fail together. Call $pdo->beginTransaction(), run the statements, then commit(). On an exception, call rollBack().

Q23. How do you avoid N+1 queries?

Load related data in one query, using a JOIN or an IN list, instead of one query per row. In Laravel, use eager loading with with().

Level 5: Security

Security questions are asked in almost every PHP round. Know these by heart and say how you would test each one.

Q24. What is SQL injection, and how do you prevent it?

Attacker input changes the SQL query. Prevent it with prepared statements and bound parameters, never by joining strings. Limit database user rights to what the application needs.

Q25. What is cross-site scripting, and how do you prevent it?

Attacker-supplied script runs in another user's browser. Prevent it by escaping output for HTML with htmlspecialchars($value, ENT_QUOTES, 'UTF-8'), validating input, and setting a Content Security Policy. Template engines such as Blade escape by default.

Q26. What is cross-site request forgery, and how do you stop it?

A malicious site makes a logged-in user's browser send a request. Stop it with a CSRF token in each form, checked on the server, and with SameSite cookies. Use the framework's CSRF middleware where it exists.

Q27. How do you store passwords?

Use password_hash($password, PASSWORD_DEFAULT) and check with password_verify. Never store plain text, MD5 or unsalted SHA-256. Do not roll your own hashing.

Q28. How do you handle file uploads safely?

Check the size and the real MIME type, not only the extension. Rename the file to a random name, store it outside the web root, or in object storage. Never run an uploaded file. Restrict the allowed types.

Q29. What is the danger of eval and include with user input?

They run code from input. Local file inclusion or remote file inclusion can lead to full compromise. Never pass user input to eval, and never use it to build a file path without a strict allow-list.

Q30. What should php.ini settings be in production?

Turn off display_errors so users do not see stack traces, log errors to a file, set expose_php off, and keep the PHP version updated. Keep allow_url_include off.

Level 6: Laravel and Eloquent

Q31. What is Laravel's request lifecycle?

The request enters public/index.php, goes through the HTTP kernel and its middleware, is matched to a route, runs the controller, and returns a response through the middleware again.

Q32. What is middleware?

A layer that runs before or after a request, used for authentication, logging, CSRF checks and rate limits. Apply it to routes or groups.

Q33. What is an Eloquent model, and what does a relationship look like?

A model maps a table to a class. Relationships are methods:

class User extends Model
{
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}

$users = User::with('posts')->get();

Q34. What is mass assignment, and how do you protect against it?

Filling many model attributes from request input at once. Protect with $fillable listing the allowed fields, or $guarded. Validate input before saving.

Q35. What are migrations and seeders?

Migrations version the database schema with code, so every environment builds the same tables. Seeders fill tables with test or default data. Write a migration for each change, and never edit one that has already run in production.

Q36. What is a queue, and when do you use one?

Work that can run later, such as sending email or resizing images, is pushed to a queue and handled by a worker. It keeps requests fast and handles retries.

Q37. How does Laravel handle caching?

Through a cache store such as Redis or the file store. Use Cache::remember for expensive reads, and clear or tag the cache when the data changes.

Level 7: Performance, testing and deployment

Q38. How do you make a PHP site faster?

Use OPcache, cache expensive queries and rendered fragments, add the right database indexes, avoid N+1 queries, move slow work to a queue, and serve static assets through a CDN.

Q39. What is OPcache?

A bytecode cache that keeps compiled scripts in memory, so PHP does not recompile them on each request. Enable it in production.

Q40. How do you test a PHP application?

PHPUnit for unit tests. Feature tests in Laravel that send HTTP requests to the application and check the response and the database. Use a separate test database, and reset it between tests.

Q41. What is Composer, and why do you commit composer.lock?

Composer manages PHP dependencies. The lock file records the exact versions installed, so every machine and server gets the same packages.

Q42. How do you deploy a PHP app without downtime?

Build the release in a new directory, install dependencies, run migrations that are backward compatible, switch a symlink to the new release, and clear caches. Keep the previous release for rollback.

Coding questions asked in PHP rounds

Write these by hand. Say the approach first.

C1. Reverse a string without strrev.

function reverseString(string $s): string {
    $out = '';
    for ($i = strlen($s) - 1; $i >= 0; $i--) {
        $out .= $s[$i];
    }
    return $out;
}

Mention that PHP strings are byte-based, so multi-byte characters need mb_ functions.

C2. Find duplicates in an array.

Use an associative array as a set. Return the values seen twice. O(n) time.

C3. Find the second largest number in an array.

Track the largest and second largest in one pass, handling duplicates. O(n).

C4. Group an array of orders by customer id.

$grouped = [];
foreach ($orders as $order) {
    $grouped[$order['customer_id']][] = $order;
}

C5. Write a SQL query to find the top three products by revenue.

SELECT product_id, SUM(amount) AS revenue
FROM order_items
GROUP BY product_id
ORDER BY revenue DESC
LIMIT 3;

C6. Write a small class for a shopping cart with add, remove and total.

Store items keyed by product id. Keep the total computed from the items, not stored separately, to avoid drift. Validate quantities.

How to answer 'explain a project'

Use the same structure as in other guides:

  1. The problem and the users.
  2. Your part and the decisions you made.
  3. The stack and the trade-off you accepted.
  4. The security and data handling, because interviewers ask about it.
  5. One bug or performance issue, with the cause and fix.

If the project is old code, say that you improved one part of it, and explain how.

Common mistakes

  • Concatenating SQL with input. Use prepared statements.
  • Printing user input without escaping. Escape on output.
  • Storing passwords with MD5. Use password_hash.
  • Using == where type matters. Use ===.
  • Changing an old migration. Add a new one.
  • Ignoring N+1 queries. Eager load related data.

A four-week preparation plan

WeekFocusOutput
1PHP 8 basics, arrays, strings, functionsSolve C1 to C4 without help
2OOP, interfaces, traits, Composer, autoloadingA small console app with tests
3Sessions, PDO, security topicsFix a deliberately vulnerable login form
4Laravel: routing, Eloquent, validation, queuesBuild a CRUD app with auth and one queued job

Frequently asked questions

Is plain PHP still asked? Yes, especially in companies with older systems. Know the language and the security basics before the framework.

Which Laravel version should I know? The current major version used by the company. Learn the routing, Eloquent and middleware ideas, which carry across versions.

What about WordPress? Know that it exists and how themes and plugins work, but focus on core PHP and a framework for most product roles.

Frequently Asked Questions

Yes. Many websites, content platforms and business systems run on PHP, and Laravel is widely used for new projects. Roles are steady, especially for developers who know Laravel and databases well.

PHP 8.x. Know named arguments, union types, match expressions, nullsafe operator, constructor property promotion and enums. State the version you are answering for.

SQL injection, cross-site scripting, cross-site request forgery and password storage. Use prepared statements, escape output, check CSRF tokens and use password_hash.

For most product and agency roles, yes. Learn Laravel after you understand plain PHP, sessions, databases and HTTP.

String and array functions, a small class, a database query with a join, and fixing a bug in a short script.

KS
· Founder and Editor

Keshav founded StudentUpdate.in and edits every recruitment notice, syllabus page and practice set the site publishes. Each notice is read from the issuing body's PDF or portal before it goes live; dates, fees, vacancy tables and eligibility rules are copied from that document, not from other websites.

Share