PHP Programming Interview Questions for Web Development
26 PHP Programming questions with answers for web development roles — 10 easy, 12 medium, 4 hard.
About PHP Programming
PHP still powers a large share of the web, including WordPress and Laravel apps. This topic covers request handling, superglobals, sessions and cookies, PDO, password hashing, OOP with interfaces and traits, Composer autoloading and PHP 8 features, plus debugging white screens, header errors and slow pages.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is PHP and how does a PHP page get processed?
PHP is a server-side scripting language widely used for websites, WordPress, Laravel apps and APIs. When a browser requests a .php file, the web server such as Apache or Nginx passes it to the PHP interpreter, usually through PHP-FPM. PHP runs the code, talks to databases if needed, and sends back plain HTML or JSON. The browser never sees the PHP source, only the generated output.
02
What is the difference between echo and print in PHP?
Both output strings. echo is a language construct with no return value and can take multiple comma-separated arguments, like echo $a, $b. print also is a construct but takes only one argument and returns 1, so it can be used inside expressions. echo is marginally faster and far more common. For formatted output, printf or sprintf are used, for example printf('%.2f', $price).
03
What is the difference between sessions and cookies in PHP?
A cookie stores data in the browser and is sent with every request, so users can see and edit it. A session stores data on the server and keeps only a session id in a cookie, usually PHPSESSID. Use $_SESSION for login state and cart data, after calling session_start(). Use cookies only for non-sensitive preferences, and mark session cookies HttpOnly, Secure and SameSite.
04
Explain include, require, include_once and require_once.
All four insert another PHP file. If the file is missing, include gives a warning and continues, while require throws a fatal error and stops the script. The _once versions skip the file if it was already loaded, which prevents 'cannot redeclare function' errors. Use require_once for essential files like config and database connection. Modern projects rely on Composer autoloading instead of manual includes for classes.
Superglobals are built-in arrays available in every scope without the global keyword. Common ones are $_GET and $_POST for request data, $_REQUEST combining them, $_SESSION, $_COOKIE, $_FILES for uploads, $_SERVER for headers and paths, and $_ENV for environment variables. All user-supplied superglobals must be treated as untrusted input and validated, for example using filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL).
Use prepared statements so input is never part of the SQL text:
$pdo = new PDO('mysql:host=localhost;dbname=school;charset=utf8mb4', $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$stmt = $pdo->prepare('INSERT INTO students (name, email) VALUES (:name, :email)');
$stmt->execute([
':name' => $_POST['name'],
':email' => $_POST['email']
]);
echo 'Saved with id ' . $pdo->lastInsertId();
The utf8mb4 charset supports all Unicode, including Hindi text and emoji.
07
Use the PHP 8 match expression instead of a switch.
match returns a value, uses strict comparison and needs no break:
$status = 'shipped';
$label = match ($status) {
'pending' => 'Order received',
'shipped', 'in_transit' => 'On the way',
'delivered' => 'Delivered',
default => 'Unknown status',
};
echo $label;
Unlike switch, match throws an UnhandledMatchError if no arm matches and there is no default, which surfaces missing cases early.
08
A PHP page shows a blank white screen. How do you debug it?
A white screen usually means a fatal error with display_errors turned off. I would check the PHP error log or server log first, for example the Apache or PHP-FPM log. On a local or staging machine I would enable error_reporting(E_ALL) and display_errors. Common causes are syntax errors, missing extensions like pdo_mysql, memory limit exhaustion, or a missing vendor folder. On production, errors should be logged, never displayed.
09
You see 'Headers already sent' warnings. What causes it and how do you fix it?
header(), setcookie() and session_start() must run before any output reaches the browser. The warning appears when something was printed earlier, such as an echo, HTML outside PHP tags, whitespace after a closing ?> tag, or a UTF-8 BOM at the start of a file. The message names the file and line that produced output. Removing closing ?> tags in pure PHP files prevents most cases.
I chose PHP because it powers a large share of websites, including WordPress, and many Indian agencies and product companies still hire PHP and Laravel developers. It is quick to deploy on almost any hosting. I started with plain PHP to understand requests, sessions and databases, then learned Laravel. In my project, a course enquiry portal, Laravel's validation and Eloquent let me deliver features in half the time.
11
How did string and number comparison with == change in PHP 8?
Before PHP 8, comparing a number with a non-numeric string converted the string to a number, so 0 == 'abc' was true, which caused security bugs. Since PHP 8, if the string is not numeric, the number is converted to a string and compared as strings, so 0 == 'abc' is now false. Using === is still recommended because it checks type and value without any conversion.
Both support prepared statements and are secure when used correctly. PDO supports around a dozen databases with the same API, has named placeholders like :email, and throws exceptions cleanly, so switching from MySQL to PostgreSQL is easier. mysqli works only with MySQL but exposes some MySQL-specific features. Most modern codebases and frameworks like Laravel use PDO under the hood, so it is the usual recommendation.
13
What is the difference between an abstract class and an interface in PHP?
An interface defines only method signatures and constants, and a class can implement many interfaces. An abstract class can contain properties, constructors and implemented methods along with abstract ones, but a class can extend only one. Use an interface to define a contract like PaymentGateway, and an abstract class to share common code among closely related classes, such as a base Controller.
Traits allow code reuse across unrelated classes, since PHP supports only single inheritance. You define a trait with methods, such as a Loggable trait with a log() method, and add it to any class using use Loggable;. Conflicts between traits are resolved with insteadof and as. Traits are handy for cross-cutting behaviour like timestamps or soft deletes, but overusing them hides dependencies and makes classes harder to understand.
15
What is Composer and how does PSR-4 autoloading work?
Composer is PHP's dependency manager. composer.json lists packages, composer.lock pins exact versions, and the vendor folder holds installed code. PSR-4 maps a namespace prefix to a folder, for example App\ to src/, so App\Models\User loads from src/Models/User.php automatically after you require vendor/autoload.php. This removes manual require statements. composer.lock should be committed so every environment installs identical versions.
PHP 8.0 added the JIT compiler, named arguments, union types, the match expression, the nullsafe operator ?-> and constructor property promotion. PHP 8.1 added enums, readonly properties, fibers and never return type. PHP 8.2 added readonly classes, 8.3 added typed class constants and json_validate, and 8.4 added property hooks and asymmetric visibility. Together they make PHP code safer, shorter and more strongly typed.
Never store plain text or use md5 or sha1, which are fast and easily cracked. Use password_hash($password, PASSWORD_DEFAULT), which currently uses bcrypt with an automatic random salt, or PASSWORD_ARGON2ID where available. At login use password_verify($input, $hash). password_needs_rehash lets you upgrade old hashes when the default algorithm or cost changes. The hash column should be VARCHAR(255) to allow future algorithms.
MVC separates an application into Models for data and business rules, Views for presentation, and Controllers that handle requests and connect the two. In Laravel, routes send a request to a controller, the controller uses Eloquent models to query the database, and returns a Blade view or JSON. This separation makes code testable and lets frontend and backend developers work on different layers without conflicts.
19
Write a PHP login script using password_verify and sessions.
Likely causes are session_start() missing on the next page, output sent before session_start so headers fail, or the session cookie being dropped. Cookie issues include a Secure flag on an HTTP site, a domain mismatch between www and non-www, or SameSite settings during cross-site redirects. I would check the Set-Cookie header in DevTools, verify session.save_path is writable, and redirect to a single canonical domain.
22
Tell me about a time you had to work with messy legacy code.
Situation: I joined a project with a 10-year-old PHP codebase full of mixed HTML and SQL. Task: I needed to add online payments without breaking existing features. Action: I wrote tests around the checkout flow first, extracted database code into a small class using PDO, and added the payment module separately. Result: payments launched with no regressions, and the team adopted the same approach for later changes.
By default PHP coerces scalar types, so passing '5' to a function expecting int silently works. With declare(strict_types=1) at the top of a file, calls made from that file must pass exactly the declared types, or a TypeError is thrown. It catches bugs early, especially in APIs where values arrive as strings. It applies per file, to calls made from the file, not to the whole project.
Check errors, size and real MIME type, then store with a random name:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK && $_FILES['photo']['size'] < 2_000_000) {
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($_FILES['photo']['tmp_name']);
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
if (isset($allowed[$mime])) {
$name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
move_uploaded_file($_FILES['photo']['tmp_name'], __DIR__ . '/uploads/' . $name);
}
}
Never trust the original filename or extension.
25
A PHP page takes 8 seconds to load. How do you find the bottleneck?
I would measure before guessing, using a profiler like Xdebug or Blackfire, or simple microtime logs around sections. Usually the cause is database queries, such as an N+1 pattern running a query inside a loop, missing indexes, or slow external API calls. Fixes include joining or eager loading, adding indexes, caching results in Redis, making API calls async with a queue, and enabling OPcache.
26
You must upgrade an old project from PHP 7.4 to PHP 8.3. How do you plan it?
I would first set up a staging copy and run a static analyser like PHPStan or Rector with PHP 8 rules to list incompatible code, such as removed functions, changed string comparisons and stricter type errors. Then I would update Composer dependencies to versions supporting PHP 8.3, fix deprecations, run the test suite and manual checks, and deploy with a rollback plan. PHP 7.4 has been unsupported since 2022.
Frequently asked questions
How important is PHP Programming in Web Development interviews?
PHP still powers a large share of the web, including WordPress and Laravel apps. This topic covers request handling, superglobals, sessions and cookies, PDO, password hashing, OOP with interfaces and traits, Composer autoloading and PHP 8 features, plus debugging white screens, header errors and slow pages.
How should I use the PHP Programming sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.