Here are 100 PHP interview questions and answers, covering fundamentals, syntax, OOP, arrays, strings, file handling, sessions, cookies, databases, security, and modern PHP (7.x, 8.x). Each question is in bold, followed by a detailed answer. No dividing lines.
What is PHP and what does it stand for?
Answer: PHP stands for Hypertext Preprocessor (originally Personal Home Page). It is a server-side scripting language designed primarily for web development but also used as a general-purpose language. PHP code is executed on the server, generating HTML that is sent to the client.
What is the difference between echo and print in PHP?
Answer: echo is a language construct (not a function) that can output multiple strings separated by commas and returns no value. print is a function-like construct that takes one argument and returns 1 (always). echo is slightly faster, but both are used to output strings.
How do you declare a variable in PHP?
Answer: PHP variables start with a dollar sign ($) followed by the variable name. They are case-sensitive. Example: $name = "John";. Variables do not need explicit type declaration; PHP is dynamically typed.
What are the different data types in PHP?
Answer: Scalar types: int, float, string, bool. Compound types: array, object, callable, iterable. Special types: resource, NULL.
What is the difference between == and === in PHP?
Answer: == (equal) compares values after type coercion (e.g., 0 == "0" is true). === (identical) compares both value and type without coercion (0 === "0" is false). Use === to avoid unexpected type juggling.
What are the three types of arrays in PHP?
Answer: Indexed arrays (numeric keys), associative arrays (string keys), and multidimensional arrays (arrays containing other arrays). PHP arrays are actually ordered maps that can hold keys of any type.
How do you connect to a MySQL database using PHP?
Answer: Using mysqli (MySQL improved) or PDO (PHP Data Objects). Example with mysqli: $conn = new mysqli("host", "user", "password", "database");. Example with PDO: $pdo = new PDO("mysql:host=host;dbname=database", "user", "password");.
What is the difference between include and require?
Answer: Both include and evaluate a file. require produces a fatal error (E_COMPILE_ERROR) and stops the script if the file is not found. include only produces a warning (E_WARNING) and the script continues. require_once and include_once prevent multiple inclusions of the same file.
What are sessions in PHP and how do you start one?
Answer: Sessions allow storing user data across multiple pages. Start a session with session_start() at the beginning of each page. Data is stored in the $_SESSION superglobal. Session IDs are stored in a cookie or passed in the URL.
What is the difference between session_start() and session_regenerate_id()?
Answer: session_start() starts or resumes a session. session_regenerate_id() replaces the current session ID with a new one, helping prevent session fixation attacks. Call it after login and periodically.
How do you set and retrieve cookies in PHP?
Answer: Set a cookie with setcookie(name, value, expire, path, domain, secure, httponly). Retrieve with $_COOKIE['name']. Cookies are sent in HTTP headers, so setcookie() must be called before any output.
What are the superglobals in PHP?
Answer: Predefined global arrays: $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV. They are accessible from any scope.
What is the difference between GET and POST methods?
Answer: GET appends data to the URL (visible, limited length, bookmarked, cached). POST sends data in the request body (not visible, no size limit, not cached). Use GET for idempotent read-only operations, POST for forms that change state.
How do you prevent SQL injection in PHP?
Answer: Use prepared statements and parameterized queries (PDO or mysqli). Example with PDO: $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]);. Never directly interpolate user input into SQL strings.
What is XSS (Cross-Site Scripting) and how do you prevent it?
Answer: XSS occurs when an attacker injects malicious scripts into web pages. Prevent by escaping output: htmlspecialchars($string, ENT_QUOTES, 'UTF-8') when outputting user-controlled data in HTML context. Use context‑appropriate escaping.
What is CSRF and how do you protect against it?
Answer: Cross-Site Request Forgery tricks authenticated users into unintended actions. Protect by using CSRF tokens: generate a unique token, store in session, include in forms, and validate on submission. Modern frameworks often include CSRF protection.
What is the difference between mysqli and PDO?
Answer: MySQLi is MySQL-specific, supports both procedural and OOP styles, and offers features like multiple statements. PDO is database-agnostic (supports 12 drivers), OOP-only, supports named placeholders, and is generally preferred for portability and security.
What is an autoloader in PHP?
Answer: An autoloader automatically loads class files when a class is referenced. Use spl_autoload_register() to register autoload functions. Composer’s autoloader is the most common implementation following PSR-4 standards.
What are traits in PHP?
Answer: Traits are a mechanism for code reuse in single inheritance languages. A trait is similar to a class but cannot be instantiated. Classes can use multiple traits via the use keyword. Traits can have methods, abstract methods, and properties.
What is the difference between abstract class and interface?
Answer: Abstract classes can have concrete methods, properties, and constructors. A class can extend only one abstract class. Interfaces can only declare method signatures (no implementation), and a class can implement multiple interfaces. PHP 8+ allows interfaces to have default methods (via traits) but not properties.
What is the final keyword in PHP?
Answer: final prevents a class from being extended or a method from being overridden. Example: final class MyClass {} or final public function myMethod() {}. Useful for security or design immutability.
What are magic methods in PHP? Give examples.
Answer: Magic methods are special methods prefixed with double underscore, triggered by certain actions. Examples: __construct(), __destruct(), __call(), __get(), __set(), __toString(), __invoke(), __clone(), __sleep(), __wakeup().
What is the purpose of __toString()?
Answer: __toString() defines how an object should be represented as a string. It is called automatically when an object is used in a string context (e.g., echo $obj;). The method must return a string.
What is namespace in PHP?
Answer: Namespaces organize code, prevent name collisions between classes, functions, and constants. Declared with namespace MyNamespace;. Use with use MyNamespace\MyClass;. Supports aliasing (use MyNS\MyClass as Alias;).
What is the difference between include_once and require_once?
Answer: include_once includes the file only once and throws a warning on failure. require_once includes only once and throws a fatal error on failure. Both prevent multiple inclusions.
How do you handle file uploads in PHP?
Answer: Use $_FILES superglobal and move_uploaded_file(). Check for errors ($_FILES['file']['error']). Example:
php
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.basename($_FILES['file']['name']));
}
Always validate file type and size.
What is the filter extension in PHP?
Answer: The filter extension provides functions for data sanitization and validation, e.g., filter_var(), filter_input(). Examples: filter_var($email, FILTER_VALIDATE_EMAIL), filter_var($url, FILTER_SANITIZE_URL).
What are the error types in PHP?
Answer: E_ERROR (fatal runtime error, script stops), E_WARNING (non-fatal), E_NOTICE (runtime notice), E_PARSE (compile-time parse error), E_STRICT (suggest code improvements), E_DEPRECATED, E_USER_ERROR, etc. Set error reporting with error_reporting(E_ALL).
How do you catch exceptions in PHP?
Answer: Use try, catch, and optionally finally blocks. Example:
php
try {
// code that may throw
} catch (SpecificException $e) {
// handle
} catch (Exception $e) {
// fallback
} finally {
// always executed
}
PHP 8 supports catch (Exception $e) only.
What is the difference between Exception and Error in PHP 7+?
Answer: Both implement Throwable interface. Exception is for traditional exceptions (recoverable). Error represents internal PHP errors (type errors, assertion errors) and is not caught by default catch (Exception). Use catch (Throwable) to catch both.
What are type declarations (type hints) in PHP?
Answer: Type declarations specify the expected data type for function arguments, return values, class properties (since PHP 7.4), and more. Examples: function greet(string $name): string { ... }. Supported types: scalar, class/interface, callable, array, iterable, object, mixed (PHP 8).
What is the null coalescing operator ???
Answer: ?? returns the left operand if it exists and is not null; otherwise, returns the right operand. Example: $name = $_GET['name'] ?? 'Guest';. Also works as ??= (null coalescing assignment) since PHP 7.4.
What is the spaceship operator <=>?
Answer: The spaceship operator (PHP 7+) compares two expressions. Returns -1 if left < right, 0 if equal, 1 if left > right. Useful for sorting custom comparators.
What is the difference between isset() and empty()?
Answer: isset($var) returns true if the variable exists and is not null. empty($var) returns true if the variable does not exist or its value equals false, 0, empty string, null, or empty array. empty() does not produce a warning for undefined variables.
How do you define a constant in PHP?
Answer: Using define('CONSTANT_NAME', value) or const CONSTANT_NAME = value; (within classes). Class constants are defined with const. Constants do not start with $ and are global.
What are the magic constants in PHP?
Answer: __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __TRAIT__, __METHOD__, __NAMESPACE__. They change depending on where they are used.
What is the difference between strpos() and preg_match()?
Answer: strpos() finds the position of a substring (plain text). preg_match() performs a regular expression match. strpos() is faster for simple string search. Use preg_match() for patterns.
How do you handle date and time in PHP?
Answer: Use DateTime class (recommended) or legacy functions date(), time(), strtotime(). Example: $now = new DateTime(); echo $now->format('Y-m-d H:i:s');. DateTime supports timezones, intervals, and comparisons.
What is the session_start() requirements?
Answer: session_start() must be called before any output (HTML or whitespace) is sent to the browser, because it sends HTTP headers. It also requires session storage to be writable.
What is the password_hash() and password_verify() functions?
Answer: password_hash($password, PASSWORD_DEFAULT) creates a bcrypt hash (automatically salts). password_verify($password, $hash) verifies a plaintext password against the hash. Never store plaintext passwords.
What is the difference between unset() and array_splice()?
Answer: unset($array[$key]) removes the element but does not reindex the array (preserves other keys). array_splice($array, $offset, $length) removes elements and reindexes numeric keys (if numeric). For associative arrays, unset is typical.
How do you send an email with PHP?
Answer: Using mail() function, but it requires a configured mail server. For production, use libraries like PHPMailer or SwiftMailer, which support SMTP, attachments, and HTML emails.
What is output buffering and why use it?
Answer: Output buffering (ob_start()) captures output instead of sending it immediately. Useful for modifying headers after output, compressing output, or storing content for later manipulation.
How do you prevent XSS in HTML attributes?
Answer: Use htmlspecialchars($string, ENT_QUOTES | ENT_HTML5, 'UTF-8') to escape characters that break HTML attribute boundaries. Do not rely on stripping tags.
What is a closure in PHP?
Answer: A closure is an anonymous function that can capture variables from its parent scope using use. Example: $adder = function($x) use ($y) { return $x + $y; };. Often used as callbacks.
What are anonymous functions?
Answer: Functions without a name, defined as function($param) { ... }. Can be assigned to variables or passed as arguments. They can be closures if they capture variables.
What is the yield keyword?
Answer: yield is used inside a generator function to produce a series of values lazily. The generator function returns an Generator object that can be iterated. Memory efficient for large datasets.
What is a generator in PHP?
Answer: A generator is a function that uses yield to produce values on demand, without building an entire array in memory. It simplifies iteration over large data sets or streams.
What is the difference between foreach and while(list() = each())?
Answer: foreach iterates over arrays elegantly and works with internal array pointer. while(list() = each()) is older and less efficient; each() is deprecated. Use foreach.
How do you sort an array in PHP?
Answer: sort() (ascending, reindex), rsort(), asort() (maintain key association), ksort() (sort by keys), usort() (user-defined comparison), array_multisort().
What are the array_map(), array_filter(), and array_reduce() functions?
Answer: array_map() applies a callback to each element and returns a new array. array_filter() filters elements using a callback. array_reduce() iteratively reduces an array to a single value.
What is the difference between == and === for array comparison?
Answer: == compares arrays by checking if they have the same key-value pairs (order independent, but same number of elements). === requires same key-value pairs in the same order and same types.
What is a PDOStatement?
Answer: A PDOStatement object represents a prepared statement and its result set. It is returned by PDO::prepare() and provides methods like execute(), fetch(), fetchAll(), bindParam().
What is the difference between fetch(), fetchAll(), and fetchColumn() in PDO?
Answer: fetch() retrieves one row at a time. fetchAll() retrieves all rows in an array. fetchColumn() returns a single column from the first row. fetchAll() may use more memory.
How do you handle transactions in PDO?
Answer: Use beginTransaction(), commit(), and rollBack(). Example:
php
$pdo->beginTransaction();
try {
// queries
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
Requires InnoDB engine.
What are prepared statements and why are they important?
Answer: Prepared statements separate SQL logic from data, preventing SQL injection and improving performance when executing the same query multiple times. They are the primary defense against injection attacks.
What is the __invoke() magic method?
Answer: __invoke() is called when an object is used as a function. Example: $obj = new MyClass(); $obj();. Useful for callable objects and closures.
What are the advantages of PHP 8 over PHP 7?
Answer: Attributes (annotations), named arguments, constructor property promotion, match expression, nullsafe operator (?->), union types, str_contains(), str_starts_with(), str_ends_with(), JIT (Just-In-Time compilation), and improvements to error handling.
What is the match expression in PHP 8?
Answer: match is a stricter and more powerful alternative to switch. It uses strict comparison, returns a value, and does not have fallthrough. Example: $result = match($value) { 1 => 'one', 2 => 'two', default => 'other' };.
What is the nullsafe operator ?->?
Answer: The nullsafe operator (PHP 8) allows chaining property/method calls and returns null if the left operand is null, preventing null pointer errors. Example: $city = $user?->address?->city;.
What are union types in PHP 8?
Answer: Union types declare that a parameter or return type can be one of several types. Example: function foo(int|string $input): int|string { ... }. Prior to PHP 8, only special-case ?Type (nullable) was available.
What are attributes (annotations) in PHP 8?
Answer: Attributes provide structured metadata for classes, methods, properties, etc. Syntax: #[AttributeName]. They replace docblock annotations in many use cases (e.g., routing, validation). Access via Reflection.
What is constructor property promotion in PHP 8?
Answer: Allows property declaration and initialization within the constructor signature. Example: class User { public function __construct(private string $name) {} }. Reduces boilerplate.
What is JIT (Just-In-Time) compilation in PHP 8?
Answer: JIT compiles PHP bytecode into machine code at runtime, potentially improving performance for CPU-intensive workloads. It is not a silver bullet; most web applications see modest gains.
What are the str_contains(), str_starts_with(), str_ends_with() functions?
Answer: These functions (PHP 8) simplify string checks: str_contains($haystack, $needle), str_starts_with(), str_ends_with(). They are more readable than strpos($haystack, $needle) !== false.
How do you create a REST API in PHP?
Answer: Use a framework (Laravel, Slim, Lumen) or plain PHP with routing, input handling, JSON encoding/decoding, status codes, and authentication (JWT, API keys). Return data with json_encode(), set headers: header('Content-Type: application/json');.
What is Composer and what does it do?
Answer: Composer is a dependency manager for PHP. It resolves, installs, and updates libraries. It uses composer.json to define dependencies and generates autoload.php for PSR-4 autoloading. It is essential for modern PHP development.
What is PSR (PHP Standards Recommendation)?
Answer: PSRs are standards set by the PHP-FIG (Framework Interoperability Group). Examples: PSR-1 (Basic Coding Standard), PSR-4 (Autoloading), PSR-7 (HTTP Message Interfaces), PSR-12 (Extended Coding Style). Following PSRs improves interoperability.
What is the difference between require_once and autoloading?
Answer: require_once explicitly includes a file. Autoloading loads classes on demand, reducing manual includes and improving performance by only loading needed classes.
What is the cURL extension?
Answer: cURL (Client URL) allows PHP to make HTTP requests, handle cookies, set headers, and interact with APIs. Example: $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_exec($ch);.
How do you handle file and directory operations?
Answer: Functions: fopen(), fread(), fwrite(), fclose(), file_get_contents(), file_put_contents(), mkdir(), scandir(), unlink(), rmdir(). Use is_file(), is_dir(), file_exists().
What is the $_SERVER superglobal array?
Answer: $_SERVER contains server and execution environment information. Common keys: REQUEST_METHOD, HTTP_HOST, SCRIPT_NAME, QUERY_STRING, REMOTE_ADDR, HTTP_USER_AGENT.
What is the difference between $_POST and php://input?
Answer: $_POST is populated for form data (application/x-www-form-urlencoded or multipart/form-data). php://input reads raw input (e.g., JSON, XML) and is used when $_POST is not populated (e.g., REST APIs with JSON body).
How do you restrict file upload types?
Answer: Check $_FILES['file']['type'] (not reliable; client-provided), verify extension using pathinfo($filename, PATHINFO_EXTENSION) and compare against whitelist. Also check MIME type with finfo_file() for better security.
What is the max_execution_time directive?
Answer: It limits the maximum time (in seconds) a script is allowed to run. Default 30 seconds. Can be changed with set_time_limit() or in php.ini. Prevents runaway scripts.
What are register_shutdown_function() and register_tick_function()?
Answer: register_shutdown_function() registers a callback to execute after script execution finishes or exit() is called. register_tick_function() executes a callback on each tick (low-level internal event).
What is the difference between self and static keywords (late static binding)?
Answer: self refers to the class in which it is written (compile‑time). static (late static binding) refers to the called class at runtime (useful in inheritance). Example: class A { public static function test() { return static::class; } }.
What is the purpose of __autoload() (deprecated)?
Answer: __autoload() was a magic function to autoload classes; replaced by spl_autoload_register() which supports multiple autoloaders. spl_autoload_register() is preferred.
What is the is_callable() function?
Answer: is_callable() checks if a variable can be called as a function (including closures, object methods, static methods). Returns true for valid callables.
How do you debug a PHP script?
Answer: Use var_dump(), print_r(), error_log(), and debug_backtrace(). For better debugging, use Xdebug extension (step debugging, stack traces, code coverage). Also check error logs.
What is var_dump() vs print_r()?
Answer: var_dump() displays structured information about a variable (type, length, values). print_r() prints human-readable information (simpler, no types). var_export() returns valid PHP code representation.
How do you handle timezones in PHP?
Answer: Set default timezone with date_default_timezone_set('UTC') or in php.ini. Use DateTimeZone class. Example: $tz = new DateTimeZone('America/New_York'); $dt = new DateTime('now', $tz);.
What are the array_key_exists(), isset(), and ?? differences for array keys?
Answer: array_key_exists($key, $array) returns true if key exists, even if value is null. isset($array[$key]) returns false if value is null. ?? coalesces null or missing key to default. Choose based on whether null is distinct from missing.
What is the extract() and compact() functions?
Answer: extract($array) imports variables from an array into the current symbol table (dangerous for user input). compact('var1', 'var2') creates an array from variable names and their values. Use with caution.
What is the difference between strpos() and mb_strpos()?
Answer: strpos() works on single-byte strings; it may break multibyte characters (UTF-8). mb_strpos() is multibyte-safe. For international text, use mb_ functions.
What is the hash_equals() function?
Answer: hash_equals() performs a timing-safe string comparison, protecting against timing attacks. Use when comparing passwords, signatures, or security tokens. Not affected by length leakage.
What is the htmlspecialchars() vs htmlentities()?
Answer: htmlspecialchars() converts only special characters (&, ", ', <, >). htmlentities() converts all applicable characters to HTML entities (more comprehensive). For escaping output, htmlspecialchars() is usually sufficient and safer.
What are the PHP.ini directives for security?
Answer: expose_php = Off, display_errors = Off (production), log_errors = On, allow_url_include = Off, session.cookie_httponly = On, session.cookie_secure = On (HTTPS), open_basedir restriction.
What is the __clone() magic method?
Answer: __clone() is called after an object is cloned with clone keyword. It allows modifying the cloned object’s properties (e.g., deep copy of internal object references). Default clone is shallow.
What are the __sleep() and __wakeup() methods?
Answer: __sleep() is called before serialization (must return array of property names to serialize). __wakeup() is called after unserialization to reinitialize resources (e.g., database connections).
What is serialize() and unserialize()?
Answer: serialize() converts PHP value into a storable string representation. unserialize() restores it. Do not unserialize untrusted user input due to code injection risks; use JSON for interchange.
What is the difference between json_encode() and serialize()?
Answer: json_encode() produces JSON (portable, human-readable, smaller). serialize() produces PHP-specific format (supports PHP native types, but not safe for untrusted input). Use JSON for APIs, serialize for internal cache.
How do you implement pagination in PHP?
Answer: Use LIMIT clause in SQL: LIMIT offset, limit. Calculate offset = (page - 1) * perPage. Use COUNT(*) to get total records. Build HTML links for page numbers.
What is the Header() function and its common uses?
Answer: header() sends raw HTTP headers. Examples: redirect header('Location: /url'), set content type header('Content-Type: application/json'), caching headers, download header('Content-Disposition: attachment').
What is a PHP.ini file?
Answer: php.ini is the configuration file for PHP, controlling settings like error reporting, memory limit, upload size, extensions, etc. Use phpinfo() to see current settings.
What is the difference between exit and die?
Answer: die and exit are identical – they terminate script execution. die is often used with an error message: die('Error'). exit is more common for normal termination.
What is the __DIR__ magic constant?
Answer: __DIR__ returns the directory of the current script file (equivalent to dirname(__FILE__)). Useful for building absolute file paths without relying on working directory.
What is the get_defined_vars() function?
Answer: get_defined_vars() returns an array of all defined variables in the current scope. Useful for debugging.
Why should we hire you as a PHP developer?
Answer: I have strong fundamentals (OOP, error handling, database interaction), experience with modern PHP (8.x features), and adherence to security best practices (prepared statements, output escaping). I write clean, maintainable code using Composer and PSR standards. I am comfortable with frameworks (Laravel/Symfony) but can work without them. I also enjoy solving performance issues and mentoring juniors.