PHP Interview Questions and Answers

PHP Interview Questions and Answers - EncodingCompiler

Quick answer

PHP interviews cover the language basics, such as data types, == vs ===, include vs require and superglobals, then sessions and cookies, and security: prepared statements against SQL injection, escaping output against XSS, and password_hash() for passwords. Experienced roles also ask about Composer, namespaces, object-oriented PHP, strict types, and PHP 8 features such as match, enums and the nullsafe operator.

PHP still runs a large share of the web, including WordPress, and it is the language behind frameworks such as Laravel and Symfony. Interviews for PHP roles cover the language basics, how PHP handles web requests, security, and object-oriented PHP, and increasingly the modern features added in PHP 8. This guide covers the questions asked most often, with short answers and code.

PHP Interview Questions and Answers for Freshers

PHP interview questions and answers: PHP 8 Features at a Glance
PHP 8 Features at a Glance (quick reference)

1. What is PHP?

PHP is an open-source, server-side scripting language designed for web development. PHP code runs on the server, which sends the result, usually HTML or JSON, to the browser. It can be embedded directly in HTML, and it is used to build dynamic pages, handle forms, work with databases, manage sessions and build APIs.

2. What does PHP stand for?

Today it stands for PHP: Hypertext Preprocessor, a recursive acronym. Originally it stood for Personal Home Page.

3. Who created PHP?

Rasmus Lerdorf created PHP in 1994 as a set of tools for his personal website. Andi Gutmans and Zeev Suraski later rewrote its core for PHP 3, and then built the Zend Engine that has powered PHP since PHP 4.

4. What is the Zend Engine?

The Zend Engine is the interpreter at the heart of PHP. It compiles PHP source code into opcodes, an intermediate form, and executes them. OPcache stores those compiled opcodes in memory so scripts do not have to be compiled on every request, and PHP 8 added a JIT compiler on top.

5. What is the difference between a static and a dynamic website?

A static website serves the same pre-written HTML files to every visitor, and changing a page means editing the file. A dynamic website builds pages on the server when they are requested, often from a database, so the content can differ for each user or change without editing files. An online shop showing your own order history is dynamic. PHP is used to build dynamic sites.

  • WordPress: by far the most widely used CMS, built around themes and plugins.
  • Drupal: a flexible CMS popular for large, complex sites, licensed under the GPL.
  • Joomla: an open-source CMS supported by the non-profit Open Source Matters.
  • Magento: an e-commerce platform originally created by Varien, now Adobe Commerce, with an open-source edition.

Laravel and Symfony are the most widely used. Others include CodeIgniter, CakePHP, Laminas (formerly Zend Framework) and Yii. Frameworks provide routing, database access, templating, validation and security features, so you do not build them from scratch.

8. Is PHP case-sensitive?

Partly. Variables are case-sensitive: $name and $Name are different variables. Constants and array keys are also case-sensitive. But function names, class names, method names and keywords are not: strlen() and STRLEN() call the same function. Using consistent case is still good practice.

9. What are the rules for naming variables?

  • A variable starts with a $ sign, followed by the name.
  • The name must start with a letter or underscore, not a number.
  • It can contain letters, numbers and underscores, but not spaces or symbols such as - or %.
  • Names are case-sensitive.

10. What data types does PHP support?

  • Scalar types: int, float (also called double), string and bool.
  • Compound types: array, which can be indexed or associative, and object.
  • Special types: null and resource, a reference to something outside PHP such as a file handle.

Type declarations can also use callable, iterable, mixed, void, never, and union types such as int|string.

11. What is null?

null is a type with a single value, meaning “no value”. A variable is null if it has been assigned null, has not been set, or has been unset. It is case-insensitive, though lowercase null is the usual style. is_null() returns true for it, isset() returns false, and it converts to false in a boolean context.

12. How do you define a constant?

A constant holds a value that cannot change once it is set. Constants have no $ sign, and by convention are written in capitals. You define one with the const keyword or the define() function:

const MAX_UPLOAD_MB = 10;
define('SITE_NAME', 'EncodingCompiler');

echo SITE_NAME;

const is defined at compile time and also works inside classes. define() runs at runtime, so it can be used inside conditions. Since PHP 8, all constants are case-sensitive.

13. What is the difference between echo and print?

Both output text. echo can take several arguments separated by commas and returns nothing. print takes one argument and returns 1, so it can be used in an expression. echo is slightly faster and far more common.

14. What is the difference between == and ===?

== compares values after type juggling, converting types if needed. === compares both value and type, with no conversion. "10" == 10 is true, but "10" === 10 is false. Use === by default to avoid surprises. PHP 8 made == safer when comparing numbers and strings: 0 == "abc" is now false, where it used to be true.

15. What is the difference between include and require?

Both insert another PHP file. If the file is missing, include gives a warning and the script carries on, while require gives a fatal error and stops. include_once and require_once skip the file if it has already been loaded, which prevents functions or classes being declared twice. Use require for files the script cannot run without. In modern projects, Composer’s autoloader loads most classes for you.

16. What is the difference between GET and POST?

GET sends data in the URL query string, so it is visible, can be bookmarked, has a length limit, and should only be used to fetch data. POST sends data in the request body, so it suits form submissions, file uploads, and anything that changes data. In PHP, the values are available in $_GET and $_POST. Neither is secure on its own: sensitive data needs HTTPS.

17. What are superglobals?

Superglobals are built-in arrays available everywhere in a script, without needing global:

  • $_GET and $_POST: request data.
  • $_REQUEST: GET, POST and cookie data combined.
  • $_SESSION: session data.
  • $_COOKIE: cookies sent by the browser.
  • $_FILES: uploaded files.
  • $_SERVER: server and request information, such as the request method.
  • $_ENV: environment variables.
  • $GLOBALS: all global variables.

PHP Interview Questions for Experienced Developers

PHP interview questions and answers: PHP == vs === Comparison
PHP == vs === Comparison (quick reference)

18. What is the difference between sessions and cookies?

A cookie is stored in the user’s browser and sent with every request, so it is limited in size and can be read or changed by the user. A session stores data on the server, and the browser holds only a session ID, usually in a cookie. Sessions are the right place for anything sensitive, such as who is logged in. Start one with session_start() and read and write $_SESSION, and call session_regenerate_id(true) after login to prevent session fixation.

19. How do you prevent SQL injection?

Never put user input directly into a SQL string. Use prepared statements with bound parameters, through PDO or MySQLi, so the database treats the input as data, never as part of the query:

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();

20. How do you prevent cross-site scripting (XSS)?

Escape any user-supplied data when you output it into HTML, so the browser displays it as text rather than running it as code:

echo htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');

Template engines such as Laravel’s Blade and Twig escape output automatically. A Content Security Policy header adds another layer of protection.

21. How should passwords be stored?

Never store passwords as plain text, or hash them with fast algorithms such as MD5 or SHA-1. Use password_hash(), which uses a slow, salted algorithm, bcrypt by default, and password_verify() to check a login:

$hash = password_hash($password, PASSWORD_DEFAULT);

if (password_verify($input, $hash)) {
    // correct password
}

22. What is CSRF, and how do you prevent it?

Cross-site request forgery tricks a logged-in user’s browser into sending a request to your site from another site, such as submitting a form that changes their email address. The usual defense is a random token stored in the session and included in every form, which the server checks on submission. Setting session cookies to SameSite=Lax or Strict also helps. Frameworks handle this automatically.

23. What is Composer?

Composer is PHP’s dependency manager. You list the packages your project needs in composer.json, and Composer downloads them, usually from Packagist, and generates an autoloader so their classes load automatically. It replaced PEAR, the older PHP package repository, as the standard way to share PHP code.

24. What are the PSR standards?

PSRs, PHP Standards Recommendations, are published by the PHP Framework Interop Group (PHP-FIG) so that code from different projects works together. Well-known ones include PSR-4 for autoloading, PSR-12 for coding style (since superseded by PER Coding Style), PSR-3 for logging, PSR-7 for HTTP messages, and PSR-11 for dependency injection containers.

25. What are namespaces?

Namespaces group related classes, functions and constants under a name, so two libraries can each have a class called User without clashing. They also map naturally to folder structure with PSR-4 autoloading.

namespace App\Models;

class User { }

// elsewhere
use App\Models\User;
$user = new User();

26. What is the difference between an interface and an abstract class?

An interface defines methods a class must implement, with no implementation and no properties, and a class can implement many interfaces. An abstract class can contain both implemented and abstract methods, as well as properties, but a class can extend only one. Use an interface to define what a class can do, and an abstract class to share common code among closely related classes.

27. What are traits?

A trait is a set of methods that can be reused in several unrelated classes. Since PHP classes can only extend one parent, traits are a way to share behavior without inheritance. You add one with use inside the class.

trait HasTimestamps {
    public function touch(): void {
        $this->updatedAt = new DateTimeImmutable();
    }
}

class Post {
    use HasTimestamps;
}

28. What are magic methods?

Magic methods start with two underscores and are called automatically by PHP in certain situations. Common ones are __construct() when an object is created, __destruct() when it is destroyed, __get() and __set() when reading or writing inaccessible properties, __call() when calling an inaccessible method, __toString() when an object is used as a string, and __invoke() when an object is called like a function.

29. What are type declarations and strict types?

Type declarations state what types a function accepts and returns, and what type a property holds. By default, PHP converts compatible values, so passing "5" to an int parameter works. Adding declare(strict_types=1); at the top of a file makes PHP throw a TypeError instead, which catches bugs early.

declare(strict_types=1);

function total(int $quantity, float $price): float {
    return $quantity * $price;
}

30. What are the main features added in PHP 8?

  • PHP 8.0: named arguments, union types, the match expression, the nullsafe operator ?->, constructor property promotion, attributes, and the JIT compiler.
  • PHP 8.1: enums, readonly properties, fibers, the never return type, and first-class callable syntax.
  • PHP 8.2: readonly classes, and deprecation of dynamic properties.
  • PHP 8.3: typed class constants and the json_validate() function.
  • PHP 8.4: property hooks and asymmetric visibility.

31. What is the match expression, and how does it differ from switch?

match returns a value, compares with === rather than ==, does not fall through from one case to the next, and throws an error if no arm matches. That makes it shorter and safer than switch for choosing a value.

$label = match ($status) {
    'draft'     => 'Not published',
    'published' => 'Live',
    'archived'  => 'Hidden',
};

32. What are enums?

Added in PHP 8.1, enums define a type with a fixed set of possible values, instead of using loose strings or constants. A backed enum also has a scalar value for each case, useful for storing in a database.

enum Status: string {
    case Draft = 'draft';
    case Published = 'published';
}

$status = Status::from('draft');   // Status::Draft

33. What are the null coalescing and nullsafe operators?

The null coalescing operator ?? returns its left side if it exists and is not null, otherwise its right side, and it does not raise a warning for undefined keys: $page = $_GET['page'] ?? 1;. The nullsafe operator ?->, added in PHP 8, stops a chain of calls and returns null if any part is null: $country = $user?->getAddress()?->country;.

34. How does error handling work in modern PHP?

Most errors are now thrown as objects that you can catch with try and catch. Both Exception and Error, which covers problems such as type errors, implement the Throwable interface. Use finally for clean-up code that must always run. In production, log errors rather than displaying them, by setting display_errors off and log_errors on.

35. How do you improve PHP performance?

  • Use a supported PHP 8 version, which is much faster than PHP 7 and older.
  • Enable OPcache, so compiled code is reused between requests.
  • Find slow database queries, add indexes, and avoid running queries inside loops.
  • Cache expensive results with Redis or Memcached.
  • Use a profiler such as Xdebug or Blackfire to find the real bottleneck before optimizing.
  • Move slow tasks, such as sending emails, to a background queue.
PHP interview questions and answers: include vs require in PHP
include vs require in PHP (quick reference)

Conclusion

PHP interviews have moved on from “what does PHP stand for” to how you write secure, modern PHP: prepared statements, password hashing, Composer, strict types, and the features added in PHP 8. If you can explain those clearly, alongside the basics, you will be well prepared. If you were asked a PHP question recently that is not here, share it in the comments and we can work through the answer together.

Sources and further reading

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *