Interview questions · free
PHP Developer interview questions and answers
23 questions PHP Developer interviews in India ask, grouped by the 5 skills they test, with a short model answer for each. Then the HR round every job has. Try each one out loud before you open the answer.
- 23 questions
- 5 skills
- 14 for freshers
- Updated 30 Oct 2026
First mock interview free: 3 questions, a score and feedback on each · No card needed
Answer out loud first. Read the question, say your answer as you would in the room, then open the model answer and compare. Interviewers ask follow-ups, so learn the reasoning, not the words.
PHP · Core skill
Core language
PHP has its own quirks with types, arrays and requests, and interviewers check that you know them well enough to avoid the bugs they cause in real websites.
What is the difference between == and === in PHP?Fresher
== compares values after converting types if needed (loose comparison), while === is true only if both the value and the type are the same (strict comparison). So "1" == 1 is true, but "1" === 1 is false. Loose comparison has surprises: null == false is true, and "1" == "01" is true because both look like numbers. PHP 8 removed one famous trap: 0 == "abc" was true in PHP 7 and is false now.
The classic bug is strpos(), which returns 0 when the text is at the start and false when it isn't found. if (strpos($s, 'x')) fails for position 0, so write !== false, or use str_contains() in PHP 8. Prefer === by default.
What is the difference between sessions and cookies in PHP?Fresher
A cookie is stored in the user's browser and sent with every request to your site. You set it with setcookie() before any output is sent, and the user can read or change it, so never store anything sensitive or trusted in it. A session stores data on the server. The browser keeps only a random session ID, in a cookie named PHPSESSID by default, and PHP uses it to load the right data into $_SESSION after you call session_start().
So use sessions for login state and cart contents, and cookies for harmless preferences like a theme or language. Set the session cookie's HttpOnly, Secure and SameSite flags.
What are superglobals in PHP? Why is it a bad idea to use $_REQUEST?Fresher
Superglobals are built-in arrays available in every scope without declaring them. $_GET holds query string values, $_POST holds form data sent by POST, $_COOKIE holds cookies, $_FILES holds uploads, $_SESSION holds session data, $_SERVER holds request and server details such as REQUEST_METHOD, and $_ENV holds environment variables.
$_REQUEST mixes GET, POST and, depending on settings, cookie values into one array, so you can't tell where a value came from, and a value in the URL can quietly replace the one you expected from a form. Read from the specific array instead. Whichever you use, treat every value as untrusted: validate it, for example with filter_input() or filter_var(), and escape it when you output it.
How would you sort an array of products by price, and by name when prices are equal?1-6 years
Use usort() with a comparison function. The spaceship operator <=> returns -1, 0 or 1, and it compares arrays element by element, which makes multi-key sorting short: usort($products, fn($a, $b) => [$a['price'], $a['name']] <=> [$b['price'], $b['name']]);. For price from highest to lowest, swap $a and $b for that key.
usort() reindexes the array; use uasort() to keep the keys, and uksort() to sort by key. sort() and rsort() work on simple values, and asort() and ksort() keep keys. Since PHP 8.0, sorting is stable, so equal elements keep their original order. For large data, sort in the SQL query with ORDER BY instead of in PHP.
Arrays in PHP are passed to functions by value. What does that cost with large arrays, and what's the risk of using references in a foreach loop?1-6 years
Passing by value doesn't copy the array at once: PHP uses copy-on-write, so the function shares the same data until it modifies the array, and only then is a copy made. So passing a large array to read it is cheap. Pass by reference (&$items) only when the function must change the caller's array, and say so in its name; returning a new array is often clearer. Objects are always passed as handles, so changes to their properties are visible to the caller.
The foreach trap: after foreach ($items as &$item), $item still points to the last element. A later foreach ($items as $item) overwrites that element. Call unset($item) right after a by-reference loop.
PHP · Core skill
OOP
Modern PHP work, in Laravel, Symfony or custom code, is object-oriented and built with Composer, so interviewers move quickly from syntax to classes, namespaces and dependencies.
What is a trait in PHP, and how is it different from an interface or an abstract class?Fresher
A trait is a set of methods, and optionally properties, that you copy into a class with the use keyword. PHP allows only single inheritance, so traits let unrelated classes share code, such as a HasTimestamps or a LogsActivity trait. A trait isn't a type: you can't type-hint it, and instanceof doesn't work with it.
An interface is a contract with no implementation; it is a type, and a class can implement many. An abstract class can have both implemented and abstract methods, holds shared state, and a class can extend only one. If two traits have a method with the same name, you resolve it with insteadof, and rename one with as. Overusing traits can hide where behaviour comes from.
What are namespaces in PHP, and how does Composer's autoloading work?Fresher
Namespaces group classes and prevent name clashes, so your App\Models\User and a library's User class can coexist. You declare one at the top of a file with namespace App\Models; and import others with use.
Composer's autoloader loads a class file the first time the class is used, so you don't write require for each file. With PSR-4, composer.json maps a namespace prefix to a folder, for example App\ to src/, so App\Models\User is loaded from src/Models/User.php. You include vendor/autoload.php once, at the entry point. After changing the autoload settings, run composer dump-autoload. A common error is a file or folder name that doesn't match the class name's case, which works on Windows but fails on a Linux server.
What is the difference between composer install and composer update? Why should composer.lock be committed?1-6 years
composer update reads the version ranges in composer.json, such as ^10.0, finds the newest versions that fit, installs them and rewrites composer.lock with the exact versions chosen. composer install installs exactly the versions recorded in composer.lock, so it gives the same result every time.
Commit composer.lock so every developer, the CI server and production all run identical dependency versions; otherwise a library release between two deployments can break production with no code change from you. On production, run composer install --no-dev --optimize-autoloader. Update deliberately, ideally one package at a time with composer update vendor/package, then run the tests and review the changes before deploying.
What is the difference between self and static in PHP? What is late static binding?1-6 years
self refers to the class where the code is written. static refers to the class that was actually called at runtime; resolving it that way is called late static binding.
Suppose a base Model class has public static function create() { return new self(); }. Calling User::create() returns a Model, not a User, because self is fixed to Model. With return new static(), User::create() returns a User. The same applies to static::method() versus self::method() when a child class overrides the method. That's why frameworks use static in base classes, such as active-record models and factory methods. Return type static, allowed since PHP 8.0, documents this behaviour.
Databases
SQL
Most PHP applications run on MySQL or MariaDB, and the developer usually writes the queries by hand, so interviewers test real queries and slow-page debugging.
Write a query to show each customer's number of orders and total amount, only for customers who have spent more than ₹10,000.Fresher
SELECT c.id, c.name, COUNT(o.id) AS order_count, SUM(o.amount) AS total_spent FROM customers c JOIN orders o ON o.customer_id = c.id GROUP BY c.id, c.name HAVING SUM(o.amount) > 10000 ORDER BY total_spent DESC;
The join links each order to its customer, GROUP BY makes one row per customer, and HAVING filters the groups after the totals are calculated; WHERE can't use SUM() because it filters rows before grouping. Every column in SELECT should either be in GROUP BY or inside an aggregate; MySQL's default ONLY_FULL_GROUP_BY mode enforces this. If you wanted customers with no orders as well, you'd use a LEFT JOIN, but they'd fail this HAVING condition anyway.
In MySQL, every user needs a unique email and every order must belong to a real customer. Which keys would you use, and how do primary, unique and foreign keys differ?Fresher
A primary key uniquely identifies each row. It can't be NULL, and a table has only one, though it can span several columns. In MySQL's InnoDB engine, the table's rows are stored in primary key order. A unique key also forbids duplicate values, but a table can have many, and in MySQL a unique column can hold several NULLs. Use it for things like email or phone number.
A foreign key links a column to the primary or unique key of another table, such as orders.customer_id to customers.id, so you can't insert an order for a customer who doesn't exist. ON DELETE CASCADE or RESTRICT decides what happens when the parent row is deleted. In MySQL, foreign keys need the InnoDB engine.
A product listing page has become slow as the products table grew. How would you find and fix the slow query?1-6 years
First find the query: enable MySQL's slow query log, or log query times in the application. Run EXPLAIN on it: type ALL means a full table scan, and "Using filesort" or a huge rows estimate are warning signs. Then fix the cause. Add an index on the columns you filter and sort by, often a composite one such as (category_id, created_at). Don't wrap indexed columns in functions, as in WHERE YEAR(created_at) = 2026; use a date range instead. A leading wildcard, LIKE '%phone', can't use a normal index. Select only the columns you need, and replace a large OFFSET with keyset pagination.
Also check the PHP code for queries inside a loop, which multiply quickly.
Web
HTML, CSS and JavaScript
PHP developers in India are usually full-stack: you build the page as well as the backend, so expect questions on HTML, CSS and JavaScript.
You're building the page template in PHP. Which HTML elements would you use for the header, menu and main content, and why does semantic HTML matter?Fresher
Semantic HTML means using elements for their meaning, not just their look: header, nav, main, article, section and footer for page structure, h1 to h6 in order for headings, button for actions and a for links, and label elements tied to form inputs. A div styled to look like a button, by contrast, means nothing to the browser.
It matters for accessibility, because screen readers and keyboard users depend on these elements to understand and move through the page; for SEO, because search engines understand the content better; and for maintenance, because the code is easier to read. Add alt text to images that carry meaning. Interviewers often ask you to fix a page built entirely from divs.
What is the difference between Flexbox and CSS Grid? How do you make a layout responsive?Fresher
Flexbox lays items out in one direction, a row or a column, and is ideal for navigation bars, button groups or centring something. Grid works in two dimensions, rows and columns together, and suits whole page layouts and card grids. They work well together: a Grid for the page, Flexbox inside each card.
For a responsive layout, add the viewport meta tag, use relative units and flexible widths instead of fixed pixels, and write mobile-first CSS with min-width media queries that add columns as the screen grows. A grid with grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)) adjusts the number of columns without any media query. Set images to max-width: 100% and test on a real phone.
How would you submit a form from a PHP page with JavaScript, without reloading the page? What should the PHP side return?1-6 years
In JavaScript, listen for the form's submit event, call event.preventDefault(), build the data with new FormData(form), and send it with fetch() as a POST, including the CSRF token. Disable the button while waiting so it isn't sent twice.
On the PHP side, validate everything again, never trusting the browser's checks, then return JSON: set header('Content-Type: application/json') and echo json_encode() of the result, with a proper status code, such as 422 with field errors for invalid input. Back in JavaScript, check response.ok, then show the errors or a success message. Insert any user text with textContent rather than innerHTML, so it can't run as a script.
Reading an answer isn't the same as giving one
In a mock interview you answer new PHP Developer questions out loud or typed, and every answer is scored, with what to fix and a stronger answer.
Application security
Secure coding (OWASP)
PHP sites are a frequent target for attacks, and many older codebases have security holes, so interviewers check that you write safe code by habit.
How do you prevent SQL injection in PHP?Fresher
Use prepared statements with bound parameters, never string concatenation. With PDO: $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?'); $stmt->execute([$email]);. The value is sent separately from the SQL, so it can't change the query. mysqli supports the same with prepare() and bind_param(). Escaping functions like mysqli_real_escape_string() are easy to get wrong and aren't a substitute.
Placeholders work only for values. If a user chooses the sort column or direction, check it against a fixed list of allowed names before putting it in the query. Also set PDO to throw exceptions on errors, and connect with a database user that has only the permissions the app needs.
What is XSS, and how do you prevent it in a PHP application?Fresher
Cross-site scripting happens when user input is shown on a page without escaping, so the browser runs it as code. For example, a comment containing a script tag runs in every visitor's browser and can steal their session or change the page.
The main defence is escaping output for the place it appears. In HTML, use htmlspecialchars($value, ENT_QUOTES, 'UTF-8') every time you echo user data. Template engines like Blade and Twig escape by default; be careful with their raw output options. In JavaScript, pass data with json_encode(), and in the DOM use textContent instead of innerHTML. Add HttpOnly to session cookies and a Content Security Policy as extra layers. Validating input helps, but it doesn't replace escaping.
How should a PHP application store passwords and protect user logins?1-6 years
Store passwords with password_hash($password, PASSWORD_DEFAULT) and check them with password_verify(). It uses a slow, salted algorithm (bcrypt today), and password_needs_rehash() lets you upgrade old hashes when a user logs in. Never use md5() or sha1(), and never store passwords in a form that can be decrypted.
For the session: call session_regenerate_id(true) right after login to prevent session fixation, set the session cookie's HttpOnly, Secure and SameSite flags, and expire idle sessions. Protect forms with a CSRF token generated with random_bytes() and compared with hash_equals(). Limit failed login attempts per account and IP. Keep database passwords and API keys in environment variables, not in the code repository.
Every job
HR and behavioural round
PHP jobs are often at web agencies, startups and e-commerce companies, so the HR round looks for practical builders who can handle clients, changing requirements and several projects at once.
Can you show us something you've built? Do you have a portfolio or a GitHub profile?Fresher
For PHP roles, a working project often counts more than marks, so prepare for this. Have two or three projects ready to show on your phone or laptop, with live links if possible, and code on GitHub with a clear README. Walk through one in a minute: "This is [project], a [booking site / small online store] for [who]. I built it with PHP [and Laravel], MySQL and JavaScript. I handled [login, payments, admin panel], and the hardest part was [problem], which I solved by [how]."
Remove passwords and keys from the code before sharing it. If you have no live project yet, build a small one before interviews; it's worth the effort.
PHP is often called an old language. Why do you want to work with it?Fresher
Answer with facts and your own reason, not defensively. PHP still runs a very large share of websites, including WordPress, many e-commerce stores and a lot of business applications, so there's steady work. Modern PHP is fast and has types, enums and strong frameworks like Laravel and Symfony. For example: "I like that PHP lets me build and ship a complete web application quickly. In [project] I went from idea to a live site in [weeks] with Laravel. I also want to keep learning, so I'm comfortable with JavaScript and would pick up other languages as needed."
Show that you know current PHP, not only old tutorials.
Are you comfortable handling several small client projects at the same time?Fresher
Agencies often ask this, so show a method, not just "yes". For example: "Yes. In my internship I worked on [two or three] client sites at once. I kept a task list for each, with deadlines, blocked time for focused work instead of switching every hour, and gave each client a short update so nobody was surprised. When two deadlines clashed, I told my lead early and we agreed on the order."
Mention the tools you used, such as Trello, Jira or a shared sheet. Interviewers want to hear that you plan, communicate early and keep track of small details across projects.
A client keeps changing the requirements in the middle of a project. How do you handle it?1-6 years
Stay positive, because changes are normal, but make their cost visible. Structure: understand the change and why it's needed, explain its effect on time and cost, agree in writing, then deliver. For example: "On an e-commerce project, the client asked for a new discount system a week before launch. I asked what problem it solved, estimated it at four days, and offered two options: launch on time with a simple coupon code and add the full system after, or move the date. They chose the first, and I confirmed it by email."
Never accept a big change silently and then miss the deadline.
Tell me about a mistake you made in production. What did you learn?1-6 years
Choose a real but contained mistake, and spend most of the answer on how you fixed it and what you changed. For example: "I once ran a manual UPDATE on a client's live site with a WHERE condition I hadn't checked first, and it changed prices for more products than intended (situation). I told my lead at once, put the site into maintenance mode and restored the prices from that morning's backup within [time] (action). Since then I always run a SELECT with the same condition first, take a backup before manual changes, and use a staging copy."
Owning the mistake quickly is what interviewers are looking for. Never blame someone else.
Free interview questions, roadmaps and mock interviews: https://myskillgrid.com/interview-questions/php-developer/
Ready to answer them for real?
Your first PHP Developer mock interview is free: 3 questions, a score and feedback for each, and a stronger answer to learn from, in about 10 minutes.