Skip to main content

PHP Interview Cheat Sheet

Top 50 interview questions with concise answers. Print this page or save as PDF for offline study.

View All PHP Questions

1. What is PHP and where is it commonly used?

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development. Runs on the server and generates HTML sent to the browser. Powers 77% of websites including WordPress, Facebook (historically). Easy to embed in HTML files. Runs on Linux/Windows/Mac via Apache or Nginx with PHP-FPM. Modern PHP (8+) is fast, type-safe, and supports OOP fully.

2. What does server-side scripting mean in PHP?

Server-side scripting means the code runs on the web server, not in the browser. PHP processes the request, executes logic (DB queries, business rules), and generates the output (HTML or JSON) that is sent to the client. The client never sees PHP code - only the output. Contrast with client-side scripting (JavaScript) which runs in the browser.

3. What is the difference between echo and print?

echo: outputs one or more strings, slightly faster, no return value, can use without parentheses. print: outputs one string and returns 1, can be used in expressions. In practice they're interchangeable for simple output. echo is more commonly used. Neither is a function - both are language constructs. echo "Hello"; is the standard way to output text in PHP.

4. What are PHP variables and how are they declared?

PHP variables start with $ sign followed by a letter or underscore. Dynamically typed - no type declaration needed (though type hints are supported in PHP 7+). $name = "Alice"; $age = 25; $price = 9.99; $active = true. Variable names are case-sensitive. PHP 8 added typed properties and union types. Variables don't need to be declared before use.

5. What are PHP data types?

PHP data types: Scalar (int, float, string, bool), Compound (array, object), Special (null, resource). PHP is dynamically typed - a variable can change type. PHP 8 added union types (int|string), nullable types (?string), enums, and fibers. Use gettype() to check runtime type. Strong type declaration per file with declare(strict_types=1).

6. What is an associative array in PHP?

Associative array uses string keys instead of numeric indexes. $user = ["name" => "Alice", "age" => 25]. Access: $user["name"]. Add: $user["email"] = "alice@example.com". Remove: unset($user["age"]). Check key exists: array_key_exists("name", $user) or isset($user["name"]). Iterate: foreach($user as $key => $value). Like a dictionary/hash map in other languages.

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

== (loose comparison): compares values with type coercion - "1" == 1 is true, "" == false is true, "0" == false is true. === (strict comparison): compares both value and type - "1" === 1 is false. Always use === in PHP to avoid unexpected type juggling behavior. The loose comparison table in PHP has many non-obvious results that cause bugs.

8. What are PHP superglobal variables?

Superglobals are built-in global arrays accessible from any scope. $_GET (URL query params), $_POST (form data), $_REQUEST (GET+POST+COOKIE), $_SESSION (session data), $_COOKIE (cookie values), $_SERVER (server/request info), $_FILES (file upload data), $_ENV (environment variables), $GLOBALS (all global variables). Always validate and sanitize superglobal data before use.

9. What is the role of $_GET and $_POST?

$_GET: data from URL query string (?name=Alice&age=25). Visible in URL, bookmarkable, cached. Use for read operations (search, filtering). $_POST: data from form body (not in URL). More secure for sensitive data, not cached. Use for write operations (login, form submission). GET has length limits; POST supports large data and file uploads. Validate both before use.

10. What is a session in PHP?

Session stores data on the server between requests. session_start() initializes it. Data stored in $_SESSION["key"] = value. Session ID sent to client via cookie (PHPSESSID). On next request, client sends the ID and PHP loads the session data. Sessions expire on browser close (or timeout). More secure than cookies (data on server). Store user ID in session, not sensitive data like passwords.

11. What is a cookie in PHP?

Cookies store small data in the browser sent with every request to the domain. setcookie("name", "value", expiry, path, domain, secure, httponly). Accessible via $_COOKIE["name"]. Persist across browser sessions (based on expiry). Less secure than sessions (data on client). Use for: remember me functionality, user preferences, tracking. Set HttpOnly=true (prevents JS access) and Secure=true (HTTPS only).

12. What is the include statement used for?

include() inserts the content of one PHP file into another at runtime. If the file is not found, it shows a warning but script continues. Use for optional file inclusions (template partials, optional config). include_once ensures the file is included only once even if include is called multiple times - prevents function redeclaration errors.

13. What is the difference between include and require?

include: shows warning if file not found, script continues. require: shows fatal error if file not found, script stops. Use require for files that are essential (DB config, core functions) - the app can't run without them. Use include for optional files. Both have _once variants that prevent re-including the same file: require_once and include_once.

14. What is form handling in PHP?

PHP form handling: HTML form POSTs to PHP script. PHP reads $_POST["fieldname"] for each field. Validate: check required fields are set and not empty, validate format (email, numbers). Sanitize: strip or escape dangerous characters (htmlspecialchars for output, parameterized queries for DB). Respond: process data, redirect with header() to prevent double-submit, or show errors.

15. What is the purpose of htmlspecialchars()?

htmlspecialchars() converts special HTML characters to their entities: & to &, < to <, > to >, " to ". Use before outputting user-supplied data in HTML to prevent XSS (Cross-Site Scripting) attacks. Always use: echo htmlspecialchars($userInput, ENT_QUOTES, "UTF-8"). htmlentities() converts more characters but htmlspecialchars() is usually sufficient.

16. What is PDO in PHP?

PDO (PHP Data Objects) provides a unified interface for database access across different databases (MySQL, PostgreSQL, SQLite, etc.). Supports prepared statements (prevent SQL injection). OOP interface. Connection: new PDO("mysql:host=host;dbname=db", $user, $pass). Query: $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute([$id]); $rows = $stmt->fetchAll().

17. What is SQL injection and how do you prevent it in PHP?

SQL injection: attacker adds SQL code in user input that gets executed by the database. Prevention: always use prepared statements (parameterized queries): $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]). Never concatenate user input into SQL strings. Also: validate/sanitize input, use least-privilege DB accounts, and escape output properly.

18. What is the use of isset() in PHP?

isset() checks if a variable is set (exists) and is not null. Returns true if the variable exists and has a non-null value. Returns false if undefined or null. Use before accessing potentially undefined variables (like $_GET["param"]) to avoid "undefined index" notices. isset($_GET["page"]) is the standard pattern for optional query parameters.

19. What is empty() in PHP?

empty() returns true if a variable is: not set, null, false, 0, 0.0, "0", "" (empty string), or [] (empty array). Different from isset() - empty also catches zero and empty strings. Use empty() when you want to check if a value is meaningless/absent. Caution: empty(0) is true, so use carefully with numeric values. isset($var) && $var !== "" is more explicit.

20. How does PHP handle errors?

PHP error handling: error_reporting() sets which errors to report. display_errors=On shows errors in browser (development only - never in production). error_log() writes to log file. set_error_handler() installs a custom error handler. try/catch for exceptions. set_exception_handler() for uncaught exceptions. In production: log errors, never display them to users. Use a logging library like Monolog.

21. What is the purpose of php.ini?

php.ini is the main config file for PHP. Controls memory limit, upload size, error reporting, session settings, timezone, and extension loading. Located at /etc/php/php.ini (Linux). PHP reads it on startup. Changes need a server restart. Use phpinfo() to see what values are active. Each project can override with per-directory .user.ini files.

22. What is file handling in PHP?

PHP file handling: fopen() opens a file with a mode (r for read, w for write, a for append). fread(), fgets() for reading. fwrite() for writing. fclose() to close. file_get_contents() reads an entire file as a string. file_put_contents() writes a string to a file. Always close files after use and check for errors.

23. What is the difference between single and double quotes in PHP?

Single quotes treat content as literal text - no variable interpolation, minimal escape sequences. Double quotes parse variables and escape sequences like newlines. Single quotes are slightly faster. Use double quotes when you need variables embedded in the string. Use single quotes for static strings. Both are valid, consistency matters most.

24. What is the purpose of the header() function?

header() sends raw HTTP headers to the browser. Must be called before any output. Used for: redirects (Location header), setting content type (Content-Type: application/json), caching headers (Cache-Control), file download prompts (Content-Disposition). Always call exit after a redirect header to stop script execution immediately.

25. What is JSON encoding and decoding in PHP?

json_encode() converts PHP arrays/objects into a JSON string. json_decode() parses a JSON string into PHP objects or arrays (pass true as second arg for arrays). Returns null on failure. Check json_last_error() for error details. Used heavily for API responses. JSON is the standard data format for REST APIs and config files.

26. What is the difference between GET and POST methods in PHP?

GET sends data in the URL query string - visible, bookmarkable, cached, length-limited. Use for read-only operations like search. POST sends data in the request body - not visible in URL, supports large payloads and file uploads. Use for write operations like form submission or login. Both need validation before use.

27. What is PHP’s type juggling and how does it affect comparisons?

Type juggling is PHP automatically converting types during comparisons. Using == (loose comparison), "1" equals 1, and empty string equals false. This can cause bugs. Always use === (strict comparison) which checks both value and type. PHP 8 fixed many loose comparison inconsistencies. Explicit type casting or strict_types declaration helps avoid juggling issues.

28. What is the purpose of filter_var() in PHP?

filter_var() validates and sanitizes data. FILTER_VALIDATE_EMAIL checks email format. FILTER_SANITIZE_STRING removes tags. FILTER_VALIDATE_INT validates integers. FILTER_VALIDATE_URL checks URL format. Cleaner than writing regex manually. Use for validating user input at entry points. Part of PHP built-ins, no extra library needed.

29. What are magic constants in PHP?

Magic constants change value depending on where they are used. __LINE__ gives current line number, __FILE__ gives full file path, __DIR__ gives directory path, __CLASS__ gives class name, __METHOD__ gives method name, __NAMESPACE__ gives current namespace. Useful for debugging, logging, and building autoloaders. Always available without any import.

30. What are magic methods in PHP?

Magic methods are automatically called by PHP in certain situations. __construct runs on object creation, __destruct on cleanup, __get and __set handle undefined property access, __call handles undefined method calls, __toString is called when object is cast to string, __invoke when object is called as a function. They give objects custom behavior for built-in PHP operations.

31. What is the difference between include_once and require_once?

include_once and require_once track which files have been loaded and skip re-loading them. This prevents errors from redeclaring classes or functions. require_once causes a fatal error if the file is not found; include_once shows only a warning. Use require_once for class files and libraries where double-loading would cause redeclaration errors.

32. What is the purpose of session_start()?

session_start() must be called at the top of every page using sessions, before any output. It reads the session ID from the cookie, loads saved session data, and makes the session array available. Without it the session array does not exist. After starting a session you can store and read user data across multiple page requests.

33. What is output buffering in PHP?

Output buffering stores PHP output in memory instead of sending it directly to the browser. ob_start() starts buffering. ob_get_clean() returns the buffered content and clears it. Benefits: lets you set headers after output begins, manipulate output before sending, compress responses. Frameworks use it to wrap layout templates around content.

34. What are PHP traits?

Traits enable code reuse in PHP single-inheritance. A trait defines methods that can be mixed into any class. A class can use multiple traits. Unlike interfaces, traits provide actual implementations. Use traits for shared behaviors like logging, timestamps, or soft-delete across unrelated classes. Conflicts between traits are resolved with the insteadof and as keywords.

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

public: accessible from anywhere (outside the class, subclasses, same class). protected: accessible within the class and its subclasses. private: accessible only within the same class - not even subclasses. Apply to properties and methods. Default is public in PHP. Use private for internal implementation, protected for extensible behavior, public for the class's interface.

36. How does PHP handle exceptions?

PHP exceptions: throw new Exception("message") or throw new CustomException(). Catch with try-catch: try { riskyCode(); } catch (SpecificException $e) { handle(); } catch (Exception $e) { generic(); } finally { cleanup(); }. Multiple catch blocks handle different types. PHP 8 allows catching multiple types: catch (IOException|DatabaseException $e). Create custom exceptions by extending Exception.

37. What is the purpose of namespaces in PHP?

Namespaces prevent name collisions between classes, functions, and constants from different libraries. namespace App\\Models; declares the namespace. Use other namespaces: use App\\Services\\UserService;. Access without use: new App\\Models\\User(). PHP files with the same class name can coexist in different namespaces. Required for Composer autoloading and modern OOP PHP development.

38. What is autoloading in PHP?

Autoloading automatically loads class files when a class is first used. No manual require needed. PHP has spl_autoload_register() for custom autoloaders. Composer generates an optimized PSR-4 autoloader that maps namespace prefixes to directory paths. Just include vendor/autoload.php once and all classes load automatically. Essential for any modern PHP project.

39. What is Composer in PHP?

Composer is PHP's dependency manager. Define project dependencies in composer.json. composer install downloads packages to vendor/. composer update upgrades to latest versions. composer require adds new packages. It also generates the autoloader at vendor/autoload.php. PSR-4 autoloading maps namespaces to directories. Standard tool for all modern PHP projects.

40. What is the difference between == and === when comparing arrays?

For arrays, == checks if both arrays have the same key-value pairs (order does not matter, types coerced). === checks same key-value pairs in same order with same types. [1, 2] == ["0" => 1, "1" => 2] is true. [1, 2] === [2, 1] is false. Always use === for arrays when order or types matter to avoid surprises.

41. What is the purpose of htmlentities()?

htmlentities() converts special characters to HTML entities to prevent XSS attacks. < becomes < > becomes > and & becomes &. Always encode user-provided data before outputting it in HTML. htmlspecialchars() is the lighter version that only converts the five critical characters. Use ENT_QUOTES flag to also encode single quotes.

42. How do you connect PHP with MySQL using PDO?

PDO connection: create a new PDO object with DSN string (mysql:host=localhost;dbname=mydb), username, and password. Set error mode to exceptions for proper error handling. Use prepare() to create a prepared statement, bind parameters, then execute(). PDO works with multiple databases. Store connection in a singleton or use a DI container to avoid opening multiple connections.

43. What is the difference between mysqli and PDO?

mysqli is MySQL-specific. PDO supports 12+ database drivers (MySQL, PostgreSQL, SQLite, etc). PDO uses a consistent API regardless of database. mysqli has both procedural and OOP API. PDO uses only OOP. Both support prepared statements. Choose PDO for portability and consistency. Use mysqli only when you need MySQL-specific features like multiple result sets.

44. What is a callback function in PHP?

A callback is a function passed as an argument to another function. PHP accepts closures, arrow functions, function name strings, or array with object+method. Used with array_map(), array_filter(), usort(), etc. Callbacks let you customize behavior without changing the function. Closures can capture outer variables using the use keyword.

45. What is the purpose of phpinfo()?

phpinfo() outputs a full HTML page showing PHP version, build info, loaded extensions, ini settings, environment variables, and HTTP request details. Extremely useful for debugging config issues. Critical security risk in production - never expose phpinfo() publicly. Use it locally or in dev only, then remove it. One of the first tools to check when debugging a PHP setup.

46. What is the difference between require, include, require_once, and include_once in real project scenarios?

require causes a fatal error if file not found. include shows a warning but continues. require_once and include_once track loaded files and skip re-loading them. Use require for critical files (classes, config). Use include for optional template parts. The _once variants prevent redeclaration errors. In modern PHP with Composer autoloading, manual includes are rarely needed.

47. What is the role of PHP’s garbage collection mechanism?

PHP garbage collection frees memory automatically. Reference counting tracks how many variables point to each value. When count hits zero, memory is freed. PHP also has a cycle collector for circular references. gc_collect_cycles() triggers it manually. Long-running scripts (workers, daemons) need careful memory management since garbage does not get cleared between web requests.

48. What is the difference between session storage and token-based authentication?

Sessions store data on the server linked to a session ID cookie. Token-based auth (like JWT) stores the auth state in the token itself - stateless. Sessions work well for traditional server-rendered apps. Tokens work better for APIs and mobile apps since no server-side state is needed. Tokens are portable across services; sessions are tied to one server (or shared storage).

49. How does PHP handle file uploads and what security concerns exist?

PHP file uploads use multipart form data. Access via FILES superglobal. Security concerns: validate file type using mime_type (not extension), check file size, rename files before saving (never use original filename), store outside web root, scan for malware. Use move_uploaded_file() (not copy) to safely move temp files. Restrict allowed extensions at web server level too.

50. What is output escaping and why is it important in PHP apps?

Output escaping converts special characters so they cannot be interpreted as code. htmlspecialchars() prevents XSS in HTML context. Use json_encode() when outputting JSON. For SQL use prepared statements. For shell commands use escapeshellarg(). Escape at output time in the correct context. Never trust user input in output without escaping. A missed escape can lead to XSS or injection attacks.
Ready to level up? Start Practice