If you are preparing for a PHP interview, revising the basics alone may not be enough. Interviewers often ask questions that cover everyday PHP development as well as object-oriented programming, security, error handling, and newer language features. In this article, we have put together a collection of commonly asked PHP interview questions with clear and practical answers. The topics range from GET and POST, sessions and cookies, and PHP functions to interfaces, traits, namespaces, magic methods, type declarations, SQL injection prevention, CORS, named arguments, and readonly properties. Whether you are a beginner or an experienced PHP developer, these questions can help you review important concepts before your next interview.
1. What is PHP?
PHP, which stands for “Hypertext Preprocessor,” is a server-side programming language used to create dynamic web applications. Its open-source nature and broad ecosystem have made it a popular choice for developing everything from dynamic websites and custom web applications to APIs.
2. What is PEAR in PHP?
PEAR, short for “PHP Extension and Application Repository,” is a framework and distribution system designed to make reusable PHP components easier to develop, organize, and share. It provides a structured way for developers to work with commonly needed PHP functionality instead of building every component from scratch.
3. What is the difference between GET and POST methods?
GET and POST are two commonly used HTTP methods for sending data between a browser and a server. Although both can be used to submit information, they handle that data differently:
post_max_size.multipart/form-data, allowing files and other form fields to be sent together.4. What is the difference between include() and require() functions?
Both include() and require() are used in PHP to load the contents of another file into a script. This is useful when the same code or page component needs to be reused in multiple places.
The main difference appears when PHP cannot load the requested file. With include(), PHP issues a warning but generally continues executing the remaining code. With require(), the failure is treated as a fatal error, so script execution stops. Therefore, require() is commonly used when the requested file is essential for the application to work, while include() is useful when the file is optional.
5. What is the difference between unset() and unlink() functions?
unset() and unlink() are used for two different cleanup tasks in PHP. The unset() function removes a specified variable, making it unavailable in the current scope. On the other hand, unlink() is used to delete a file from the server's filesystem when you no longer need it.
6. What is the difference between echo() and print() functions?
Both echo and print can be used to display output in PHP, but they have a few differences:
echo does not return a value, whereas print always returns 1.echo can output multiple arguments when used with comma-separated values. print accepts only one argument.print can be used as part of an expression because it returns a value. echo does not return a value and therefore cannot be used in the same way.echo is traditionally considered slightly faster than print, but the difference is generally insignificant in real-world applications. Code readability and appropriate usage matter much more than this minor performance difference.In everyday PHP development, either can be used for simple output, with the choice usually depending on the situation and coding style.
7. What are Global/Super-global variables?
PHP provides a set of predefined variables called superglobals. These variables are available throughout a script, including inside functions and other scopes, without requiring them to be declared with the global keyword.
Common PHP superglobals include:
$GLOBALS — Provides access to variables in the global scope.$_GET — Contains values sent through URL query parameters.$_POST — Contains data submitted through the HTTP POST method.$_REQUEST — Can contain data from GET, POST, and COOKIE sources, depending on PHP configuration.$_SESSION — Stores session-related data.$_COOKIE — Contains values sent by the browser through cookies.$_SERVER — Provides information about the server and current request.$_FILES — Contains information about files uploaded through an HTTP request.$_ENV — Contains environment variables available to the script.These built-in variables are especially useful when PHP needs to work with information coming from the user, browser, server, environment, or an ongoing session.
8. What is the difference between session and cookie functions?
Session: A session allows PHP to keep user-related information on the server while the user moves between different pages of a website. It is commonly used for things such as login status, shopping carts, and other temporary user-specific data.
Cookie: A cookie is a small piece of data that a website asks the user's browser to store. The browser can send that data back to the server with subsequent requests, making cookies useful for remembering preferences, identifying returning users, and maintaining certain website settings.
9. How can we delete a cookie?
A cookie can be removed by sending the same cookie with an expiration time that has already passed. In PHP, this can be done using setcookie() with an expiration timestamp in the past. The browser will then remove the cookie.
10. What is an abstract class?
An abstract class is a class that cannot be instantiated directly. It is generally used as a base class when you want to provide common functionality while leaving some behavior for child classes to implement.
An abstract class can contain both normal methods and abstract methods. Any concrete child class must provide implementations for the abstract methods it inherits.
11. What is an interface?
An interface defines a set of methods that a class agrees to provide without specifying their implementation. It allows different classes to follow the same contract while still having their own implementations.
A class can implement multiple interfaces, which makes it possible to work with objects from different classes in a consistent way. This is one of the ways interfaces support polymorphic programming in PHP.
12. What is a Trait?
A trait is a mechanism for reusing methods and other members across multiple classes. It is particularly useful when several unrelated classes need to share the same functionality.
Instead of duplicating the same methods in different classes, you can place the common code in a trait and include it wherever it is needed using the use keyword.
Traits are a code-reuse feature; they do not represent a traditional parent-child inheritance relationship.
13. What are namespaces in PHP?
Namespaces provide a way to organize PHP classes, interfaces, traits, functions, and constants into separate naming spaces. They are especially helpful in larger applications where different parts of the code may otherwise use the same names.
For example, two classes can have the same short name as long as they belong to different namespaces. This helps avoid naming conflicts and keeps application code better organized.
14. What are magic methods?
Magic methods are specially named methods in PHP that are invoked automatically when particular operations occur on an object. Their names begin with two underscores, such as __construct() and __toString().
For example, __construct() runs when an object is created, while __get() can be invoked when inaccessible or non-existing properties are accessed.
PHP reserves specific method names for these special behaviors, so they should not be treated like ordinary user-defined method names.
15. Which are the magic methods in PHP?
PHP provides several magic methods, each associated with a particular object-related operation. Some commonly used ones include:
__construct() — Runs when a new object is created.__destruct() — Runs when an object is being destroyed.__call($name, $arguments) — Runs when an inaccessible or non-existing method is called.__callStatic($name, $arguments) — Runs when an inaccessible or non-existing static method is called.__get($name) — Runs when an inaccessible or non-existing property is read.__set($name, $value) — Runs when an inaccessible or non-existing property is written.__isset($name) — Runs when isset() or empty() is used on an inaccessible or non-existing property.__unset($name) — Runs when unset() is used on an inaccessible or non-existing property.__toString() — Runs when an object is treated as a string.__debugInfo() — Controls the information displayed for an object when it is passed to var_dump().There are additional magic methods in PHP, including those related to cloning and serialization. Therefore, the above list should not be treated as the complete list of every magic method available in PHP.
16. What is a static method?
A static method belongs to the class itself rather than to a particular object instance. Because of this, you can call it using the class name and the :: operator without creating an object first.
For example:
class Demo
{
public static function showMessage()
{
echo "Hello PHP";
}
}
Demo::showMessage();
Static methods are useful when the operation does not need information stored in a particular object instance.
17. What is the use of the final keyword?
The final keyword can be used to restrict inheritance and method overriding.
When a class is declared as final, another class cannot extend it. When a method is declared as final, a child class cannot override that method.
18. Which are the access modifiers in PHP?
PHP provides three main visibility modifiers:
For class properties and methods, public is the default visibility when no visibility modifier is specified.
19. Is PHP a case-sensitive language?
PHP is not completely case-sensitive in every part of the language.
For example, variable names are case-sensitive, so $name and $Name refer to different variables. Function names are generally case-insensitive when called, although using consistent lowercase naming is recommended.
Because PHP has different case-sensitivity rules for different language elements, describing PHP simply as either "case-sensitive" or "case-insensitive" can be misleading.
20. What is type hinting in PHP?
Type declarations, commonly referred to as type hinting, allow you to specify the type of value that a function or method expects or returns. They can also be used with class properties and, in newer PHP versions, other declarations.
For example:
function add(int $a, int $b): int
{
return $a + $b;
}
Here, the function expects integer arguments and declares that it returns an integer. PHP checks these declared types according to its type system and may throw a TypeError when a value does not satisfy the declaration.
21. How is a constant defined in a PHP script?
A constant is a value that is intended to remain unchanged during script execution. One way to define a named constant is by using the define() function.
For example:
define("TESTCONST", 124);
The constant can then be accessed by using its name:
echo TESTCONST;
PHP also supports defining constants with the const keyword in appropriate contexts.
22. What are the different types of arrays in PHP?
PHP arrays can be used in several ways depending on how their keys and values are organized:
A multidimensional array can itself contain indexed arrays, associative arrays, or a mixture of both.
23. What is method overriding?
Method overriding occurs when a child class provides its own implementation of a method inherited from its parent class.
The child method must follow PHP's method compatibility rules, including compatible visibility, parameters, and return types. It does not necessarily have to use an identical signature in every detail, because PHP allows certain compatible variations through its inheritance and variance rules.
24. What does "passing a variable by reference" mean?
When a variable is passed by reference, the function receives a reference to the original variable rather than working with a separate value.
As a result, changes made to the referenced parameter inside the function can affect the original variable.
For example:
function updateValue(&$amp;value)
{
$value = 100;
}
$number = 50;
updateValue($number);
echo $number; // 100
The & before the parameter indicates that the argument is passed by reference.
25. What is the purpose of the php.ini file?
The php.ini file is PHP's main configuration file. It contains settings that control various aspects of PHP's behavior, such as error reporting, resource limits, upload settings, session configuration, and other runtime options.
The exact location and configuration used by PHP can vary depending on the installation and environment.
26. What is .htaccess and what is it used for?
.htaccess is a directory-level configuration file used by the Apache HTTP Server. It allows certain Apache configuration rules to be applied to a particular directory and its subdirectories without changing the main server configuration.
Depending on the server configuration, it can be used for tasks such as URL rewriting, redirects, access control, and other Apache-supported directives.
It is therefore more accurate to describe .htaccess as an Apache configuration file rather than a PHP configuration file.
27. What is the difference between == and === in PHP?
The == operator performs a loose comparison. It compares the values after PHP applies its type-conversion rules where applicable.
The === operator performs a strict comparison. For the comparison to be true, both the value and the type must match.
For example:
10 == "10" // true
10 === "10" // false
Strict comparison is often preferred when you want to avoid unexpected results caused by type conversion.
28. How can you prevent SQL injection in PHP?
The most important step is to avoid inserting user-provided values directly into SQL statements.
A safer approach is to use prepared statements with bound parameters, available through PDO or MySQLi. The database then treats the supplied values as data rather than as part of the SQL command.
Additional good practices include:
29. How can you handle errors and exceptions in PHP?
PHP provides different mechanisms for dealing with errors and exceptions.
set_error_handler() can be used when you need a custom handler for certain PHP errors.try, catch, and finally.Exception class or another suitable exception type.The appropriate approach depends on the kind of problem being handled and the PHP version and application architecture.
30. How do you handle CORS in PHP?
CORS, or Cross-Origin Resource Sharing, is controlled through HTTP response headers. In PHP, these headers can be sent using the header() function.
For example:
header("Access-Control-Allow-Origin: https://example.com");
This allows the specified origin to make requests when the browser's CORS rules permit it.
You can also use:
header("Access-Control-Allow-Origin: *");
to allow requests from any origin in situations where that policy is appropriate. However, allowing every origin is not automatically suitable for applications that handle private or authenticated data.
Depending on the API, additional CORS headers may be required for methods, request headers, credentials, and preflight requests.
31. What are named arguments in PHP?
Named arguments allow a function or method to receive values by referring to parameter names instead of relying only on their position.
This can make calls easier to understand, particularly when a function has several optional parameters.
For example:
function sample($x = 2, $y = 4)
{
echo "X: ", $x;
echo " ";
echo "Y: ", $y;
}
sample(y: 10, x: 20);
Here, x and y are supplied by name, so their order in the function call does not need to match the order in which they were declared.
Named arguments were introduced in PHP 8.0.
32. What are readonly properties in PHP?
A readonly property is designed for a value that should be initialized and then prevented from being modified afterward.
Readonly properties must be typed. Once a readonly property has been initialized, attempting to assign a new value to it will result in an error.
For example:
class Test
{
public readonly string $teststr;
public function __construct(string $str)
{
$this->teststr = $str;
}
}
$test = new Test("Hello");
echo $test->teststr;
After initialization, the value of $teststr cannot be changed.
Readonly properties were introduced in PHP 8.1. PHP 8.4 also changed some of the scope rules around readonly properties, so code written for older PHP versions may have different behavior.