PHP Interview Questions and Answers
Language features, security, sessions, Composer and modern PHP 8 practices.
Whether you are preparing for entry-level PHP interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.
1 How do you prevent SQL injection in PHP? Medium
Never concatenate user input into SQL. Use prepared statements with bound parameters, which separate code from data.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email AND active = 1');
$stmt->execute([':email' => $email]);
$user = $stmt->fetch();
Also:
- Use PDO or mysqli with emulation disabled (PDO::ATTR_EMULATE_PREPARES => false).
- Validate and whitelist anything that cannot be bound, such as column names or ORDER BY direction.
- Apply least privilege to the database user and escape output with htmlspecialchars for XSS.
- Store passwords with password_hash and verify with password_verify.
2 Explain PHP session handling and common security concerns. Medium
Sessions persist state across stateless HTTP requests. session_start() creates or resumes a session identified by a cookie (PHPSESSID) and stores data server-side.
Security checklist:
- Regenerate the ID on privilege change: session_regenerate_id(true) after login to prevent session fixation.
- Set cookie flags: HttpOnly, Secure, and SameSite=Lax or Strict.
- Use session.use_strict_mode to reject unknown IDs.
- Store sessions outside the web root or in Redis for scale.
- Add CSRF tokens to state-changing forms.
- Set an idle timeout and destroy sessions on logout with session_destroy().
For APIs, prefer stateless tokens (JWT or opaque tokens) over PHP sessions.
3 What are PHP 8 features you use regularly? Medium
- Named arguments: htmlspecialchars(string: $s, flags: ENT_QUOTES).
- Constructor property promotion and readonly properties.
- Match expression (strict comparison, returns a value).
- Nullsafe operator: $user?->address?->city.
- Union types, mixed and static return type.
- Attributes for metadata instead of docblock annotations.
- Enums with methods and backed values.
- Fibers for cooperative multitasking.
- Throw as an expression.
- JIT compiler for CPU-bound workloads.
enum Status: string {
case Active = 'active';
case Banned = 'banned';
public function label(): string { return ucfirst($this->value); }
}
4 What is Composer and what does the autoload section do? Medium
Composer is PHP's dependency manager. It reads composer.json, resolves a version graph and writes composer.lock to pin exact versions for reproducible installs. composer install uses the lock file; composer update re-resolves it.
The autoload section generates a class map so you do not require files manually:
- PSR-4 maps a namespace prefix to a directory, e.g. "App\\": "src/". The class App\Foo\Bar loads from src/Foo/Bar.php.
- classmap scans directories; files always includes a file.
- composer dump-autoload -o builds an optimised classmap for production.
Include vendor/autoload.php at the entry point and namespaces resolve automatically.
5 How does PHP handle errors and exceptions? Medium
Modern PHP uses exceptions. Throwable is the root interface with two branches: Error (engine-level, e.g. TypeError, DivisionByZeroError) and Exception (application-level).
try {
risky();
} catch (ValidationException $e) {
// handle
} catch (Throwable $e) {
// fallback
error_log($e->getMessage());
} finally {
// always runs
}
Best practice: convert warnings to exceptions with set_error_handler, configure error_reporting(E_ALL), log errors rather than echo them, and never expose stack traces to users in production. Use a global handler via set_exception_handler and register_shutdown_function for fatal errors.
6 What is output escaping and why is it important? Medium
Output escaping encodes user-controlled data at the moment it is written into HTML so browsers treat it as text, not markup. This is the primary defence against XSS.
echo htmlspecialchars($comment, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
Rules:
- Escape on output, not on input. Store raw, encode per context (HTML, attribute, URL, JavaScript).
- Use a templating engine that auto-escapes (Twig, Blade, Laravel) to avoid forgetting.
- Combine with a Content-Security-Policy header that disallows inline scripts.
- Do not rely on strip_tags alone; it is not sufficient.
For attributes use ENT_QUOTES; for URLs use rawurlencode; inside script blocks prefer JSON encoding.
Frequently Asked Questions About PHP Interviews
What do hiring managers evaluate in PHP technical rounds?
Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.
What are the best interview tips for practicing PHP questions?
Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.