Skip to main content

Mid PHP Interview Questions

Curated Mid-level PHP interview questions for developers targeting mid positions. 20 questions available.

Last updated:

PHP Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of PHP interview questions and answers. This page contains expertly curated interview questions covering all aspects of PHP, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our PHP interview questions are designed to help you:

  • Understand core concepts and best practices in PHP
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next PHP interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic PHP concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

20 questions
Q1:

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

Mid

Answer

require stops execution if the file is missing, include only warns. require_once and include_once prevent duplicate loading. In real projects, require_once is used for config, autoloaders, and shared logic.
Quick Summary: 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.
Q2:

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

Mid

Answer

PHP uses reference counting and a cyclic garbage collector to free memory. It detects circular references and prevents memory leaks.
Quick Summary: 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.
Q3:

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

Mid

Answer

Sessions store user state on the server. Token-based auth (like JWT) stores authentication data client-side and is stateless, ideal for APIs and distributed systems.
Quick Summary: 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).
Q4:

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

Mid

Answer

PHP handles uploads via $_FILES. Security concerns: MIME validation, size limits, avoiding directory traversal, storing outside webroot, renaming files, and sanitizing filenames.
Quick Summary: 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.
Q5:

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

Mid

Answer

Output escaping prevents XSS by converting special characters using htmlspecialchars() or htmlentities().
Quick Summary: 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.
Q6:

How do prepared statements work in PDO?

Mid

Answer

Prepared statements compile SQL once and bind parameters later. They prevent SQL injection and improve repeated query performance.
Quick Summary: Prepared statements separate SQL from data. Use PDO prepare() with placeholder parameters (question marks or named placeholders). Call bindParam() or pass values directly to execute(). The database compiles the query once and runs it with different data. Parameters are never interpreted as SQL so injection is impossible. Use them for every query that includes user input.
Q7:

What is SPL in PHP and why use it?

Mid

Answer

SPL provides interfaces, iterators, and data structures like SplStack and SplQueue to write efficient, reusable code.
Quick Summary: SPL (Standard PHP Library) is a collection of data structures and interfaces. Includes SplStack, SplQueue, SplHeap, SplDoublyLinkedList, SplFixedArray for typed arrays. Also provides iterators and file handling classes. Using proper data structures improves performance over plain arrays. SplFixedArray is faster and uses less memory than array for numeric-indexed fixed-size collections.
Q8:

What PHP design patterns are commonly used at mid-level?

Mid

Answer

Common patterns: Singleton, Factory, Strategy, Decorator, Repository. These help structure scalable, maintainable code.
Quick Summary: Common PHP design patterns: Repository (abstracts data access), Service Layer (business logic separation), Factory (object creation), Strategy (swappable algorithms), Observer (event-driven behavior), Decorator (add behavior dynamically). Most PHP frameworks implement these. Repository and Service patterns are essential for clean, testable code in any mid-level PHP project.
Q9:

What is the difference between static and non-static methods?

Mid

Answer

Static methods belong to the class and do not need an instance. Non-static methods operate on object properties. Static overuse reduces flexibility.
Quick Summary: Static methods and properties belong to the class itself, not instances. Call with ClassName::method(). No dollar-this available. Non-static methods belong to objects and have access to instance state via dollar-this. Static is useful for utilities, factories, and shared state. Avoid static for anything that needs testing since it creates hidden global state and cannot be mocked easily.
Q10:

What is dependency injection in PHP?

Mid

Answer

Dependency injection provides dependencies from outside the class. It improves testability and decoupling. Frameworks like Laravel use DI containers.
Quick Summary: Dependency Injection means passing dependencies into a class instead of creating them inside. Constructor injection is most common. DI makes code testable (swap real deps with mocks), reduces coupling, and makes dependencies explicit. Frameworks like Laravel use DI containers to auto-resolve dependencies. Without DI, code is hard to test and tightly coupled to specific implementations.
Q11:

How does PHP handle JSON parsing errors?

Mid

Answer

json_decode() returns null on failure and json_last_error() provides the error code. Proper handling is required when interacting with APIs.
Quick Summary: json_decode() returns null on invalid JSON. Check json_last_error() to get the error code and json_last_error_msg() for a human-readable message. Common errors: syntax error (malformed JSON), unexpected control character, recursion depth exceeded. In PHP 7.3+ you can pass JSON_THROW_ON_ERROR flag to have it throw a JsonException instead of returning null silently.
Q12:

What is the difference between abstract classes and interfaces?

Mid

Answer

Abstract classes contain shared logic plus abstract methods. Interfaces define method signatures. Interfaces enforce capabilities; abstract classes share implementation.
Quick Summary: Abstract classes can have concrete methods and properties, and are extended with extends. Interfaces only define method signatures, implemented with implements. A class can implement multiple interfaces but extend only one abstract class. Use abstract class for shared base behavior. Use interface for defining a contract that multiple unrelated classes should follow.
Q13:

How do you secure sensitive configuration values in PHP applications?

Mid

Answer

Use environment variables, encrypted config files, or framework vaults. Never store secrets in code or public repos.
Quick Summary: Store secrets in environment variables, not in code. Use .env files (loaded by dotenv library) for local dev. Never commit .env to version control. In production, use server environment variables, secrets managers (AWS Secrets Manager, Vault), or encrypted config files. Access via getenv() or ENV superglobal. Separate config per environment (dev, staging, production).
Q14:

What is PHP’s password_hash() and why is it recommended?

Mid

Answer

password_hash() uses strong algorithms like bcrypt/argon2 with auto-salting, removing the need for manual security handling.
Quick Summary: password_hash() creates a secure hash using bcrypt or Argon2. It automatically generates and embeds a salt. password_verify() checks a plain password against the hash. Never use md5() or sha1() for passwords - they are fast and GPU-crackable. bcrypt is slow by design which makes brute-force attacks expensive. Always use these functions for storing user passwords.
Q15:

What is rate limiting and how can it be implemented in PHP?

Mid

Answer

Rate limiting restricts requests per user/IP using Redis counters, middleware, or token bucket algorithms. Prevents abuse.
Quick Summary: Rate limiting restricts how many requests a user can make in a time window. Implement with Redis counters (increment a key, set TTL). Return 429 Too Many Requests when limit is exceeded. Use sliding window or token bucket algorithm for smoother limiting. Apply to login endpoints, API routes, and signup forms. Libraries like symfony/rate-limiter simplify implementation.
Q16:

What is CSRF and how do you prevent it in PHP apps?

Mid

Answer

CSRF tricks users into unintended actions. Prevent using CSRF tokens, SameSite cookies, and referer validation.
Quick Summary: CSRF (Cross-Site Request Forgery) tricks a logged-in user into submitting a request they did not intend. Prevent with CSRF tokens: generate a unique token per session, embed it in forms, verify on submit. Frameworks auto-handle this. Also use SameSite=Strict or Lax cookie attribute. CSRF attacks exploit the fact that browsers auto-send cookies with cross-origin requests.
Q17:

What is the difference between file_get_contents and curl for HTTP requests?

Mid

Answer

file_get_contents() handles simple GET/POST. curl supports headers, auth, timeouts, redirects, and complex HTTP tasks. Preferred for APIs.
Quick Summary: file_get_contents() is simple - one line to fetch a URL. cURL is more powerful: supports custom headers, authentication, timeouts, POST data, SSL certificates, redirects, and connection reuse. Use file_get_contents() for quick simple requests. Use cURL (or Guzzle HTTP library which wraps it) for any real API integration that needs control over headers, auth, or error handling.
Q18:

What is autoloading (PSR-4) and how does it improve structure?

Mid

Answer

PSR-4 maps namespaces to folders. Composer autoloading eliminates manual include calls and keeps code organized.
Quick Summary: PSR-4 is a standard that maps PHP namespaces to file system directories. Namespace prefix App maps to src/ directory, so App\Models\User loads from src/Models/User.php. Composer implements PSR-4 autoloading automatically based on composer.json configuration. This replaces manual require statements. PSR-4 makes project structure predictable and autoloading efficient.
Q19:

What is the purpose of htaccess in PHP applications?

Mid

Answer

.htaccess configures Apache: URL rewriting, security rules, redirects, and access control per directory.
Quick Summary: htaccess is an Apache config file for directory-level settings. In PHP apps: enable URL rewriting (route all requests to index.php), block direct access to sensitive files, set PHP ini values, add security headers, and redirect HTTP to HTTPS. Essential for clean URLs in frameworks. Nginx uses server config files instead of htaccess. htaccess is read on every request so keep it lean.
Q20:

How does PHP handle timezones and why is it important?

Mid

Answer

PHP uses date_default_timezone_set() or php.ini. Correct timezone handling prevents scheduling bugs and inconsistent timestamps.
Quick Summary: PHP uses the system timezone by default (UTC recommended). Set date.timezone in php.ini or call date_default_timezone_set() at app start. DateTime and DateTimeImmutable classes handle timezone conversions. Store all dates in UTC in the database, convert to user timezone only for display. Wrong timezone handling causes bugs with DST transitions, scheduling, and log timestamps.

Curated Sets for PHP

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice