Pages

Wednesday, April 2, 2025

100 PHP Interview Questions and Answers

100 PHP Interview Questions and Answers
Basic PHP Questions
1. What is PHP?
PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development. It is open-source and can be embedded into HTML.
2. What are the common uses of PHP?
PHP is commonly used for:
  • Creating dynamic web pages
  • Handling forms and user input
  • Interacting with databases
  • Creating sessions and cookies
  • Generating PDF files, images, and other media
  • Building web applications and e-commerce sites
3. What is the difference between PHP4 and PHP5?
Major differences include:
  • PHP5 introduced full object-oriented programming support
  • Better MySQL support with the mysqli extension
  • Improved error handling with exceptions
  • New SimpleXML for XML parsing
  • SQLite database support
4. How do you execute a PHP script from the command line?
You can execute a PHP script from the command line by using the command: php filename.php
5. What is the difference between echo and print in PHP?
Both are used to output data, but with differences:
  • echo can take multiple parameters, print can take only one
  • echo is slightly faster than print
  • print returns 1, so it can be used in expressions
  • echo has no return value
Variables and Data Types
6. How do you declare a variable in PHP?
Variables in PHP are declared with a dollar sign ($) followed by the variable name. Example: $variableName = "value";
7. What are the main data types in PHP?
PHP supports eight primitive data types:
  • 4 scalar types: boolean, integer, float (double), string
  • 2 compound types: array, object
  • 2 special types: resource, NULL
8. What is the difference between == and === in PHP?
  • == checks for equality (value only)
  • === checks for identity (both value and type)
Example: 0 == "0" is true, but 0 === "0" is false
9. How do you check if a variable is set and not null?
Use the isset() function: if(isset($variable)) { ... }
10. What is variable scope in PHP?
Variable scope defines where a variable can be accessed:
  • Local scope: Only accessible within the function where declared
  • Global scope: Accessible anywhere, but needs global keyword inside functions
  • Static variables: Retain value between function calls
Operators and Control Structures
11. What are the different types of operators in PHP?
PHP has several types of operators:
  • Arithmetic operators (+, -, *, /, %)
  • Assignment operators (=, +=, -=, etc.)
  • Comparison operators (==, ===, !=, <>, !==, >, <, etc.)
  • Logical operators (&&, ||, !, and, or, xor)
  • String operators (., .=)
  • Array operators (+, ==, ===, !=, !==, <>)
12. How does the ternary operator work in PHP?
The ternary operator is a shorthand for if-else: $result = (condition) ? value_if_true : value_if_false;
13. What is the difference between break and continue?
  • break ends execution of the current loop or switch structure
  • continue skips the rest of the current loop iteration and continues with the next iteration
14. How do you write a switch statement in PHP?
Example:
switch($variable) {
    case 'value1':
        // code
        break;
    case 'value2':
        // code
        break;
    default:
        // default code
}
15. What is the purpose of the goto statement in PHP?
The goto statement allows jumping to another section in the program. Example:
goto mylabel;
// some code
mylabel:
// code to execute after goto
Note: goto is generally discouraged as it can make code harder to follow.
Functions
16. How do you define a function in PHP?
Example:
function functionName($param1, $param2) {
    // function code
    return $result;
}
17. What are variable functions in PHP?
Variable functions allow you to call a function using a variable. Example:
function hello() { echo "Hello"; }
$func = 'hello';
$func(); // Calls hello()
18. How do you pass arguments by reference?
Use an ampersand (&) before the parameter in the function definition:
function addFive(&$num) {
    $num += 5;
}
$value = 10;
addFive($value); // $value is now 15
19. What are anonymous functions in PHP?
Anonymous functions (closures) are functions without a name. Example:
$greet = function($name) {
    echo "Hello $name";
};
$greet("World");
20. How do you return multiple values from a function?
You can return multiple values by:
  • Returning an array: return array($value1, $value2);
  • Using references in parameters
  • Returning an object
Arrays
21. How do you create an array in PHP?
  • Indexed array: $array = array("apple", "banana", "cherry");
  • Associative array: $array = array("a"=>"apple", "b"=>"banana");
  • Short syntax (PHP 5.4+): $array = ["apple", "banana"];
22. How do you add an element to an array?
  • For indexed arrays: $array[] = "new value";
  • For associative arrays: $array["key"] = "value";
  • Using array_push(): array_push($array, "value1", "value2");
23. How do you sort an array in PHP?
PHP provides several sorting functions:
  • sort() - sort indexed arrays in ascending order
  • rsort() - sort indexed arrays in descending order
  • asort() - sort associative arrays by value in ascending order
  • ksort() - sort associative arrays by key in ascending order
  • arsort() - sort associative arrays by value in descending order
  • krsort() - sort associative arrays by key in descending order
24. What is the difference between array_merge and array_combine?
  • array_merge() merges two or more arrays into one
  • array_combine() creates an array by using one array for keys and another for values
Example:
$keys = ['a', 'b'];
$values = [1, 2];
$combined = array_combine($keys, $values); // ['a'=>1, 'b'=>2]
25. How do you check if a value exists in an array?
Use in_array() for values: if(in_array($value, $array)) { ... }
Use array_key_exists() for keys: if(array_key_exists($key, $array)) { ... }
Strings
26. How do you concatenate strings in PHP?
Use the dot (.) operator: $full = $str1 . $str2;
Or the concatenation assignment operator: $str1 .= $str2;
27. How do you find the length of a string?
Use strlen(): $length = strlen($string);
28. How do you replace text in a string?
Use str_replace():
$newString = str_replace("old", "new", $originalString);
29. What is the difference between single and double quotes in PHP?
  • Single quotes: Literal strings, no variable interpolation or escape sequences (except \\ and \')
  • Double quotes: Parse variables and escape sequences like \n, \t, etc.
30. How do you convert a string to lowercase or uppercase?
Use strtolower() or strtoupper():
$lower = strtolower("HELLO"); // "hello"
$upper = strtoupper("hello"); // "HELLO"
Object-Oriented PHP
31. What are the main principles of OOP in PHP?
The four main principles are:
  • Encapsulation: Bundling data and methods that work on that data
  • Abstraction: Hiding complex implementation details
  • Inheritance: Creating new classes from existing ones
  • Polymorphism: Using a single interface for different data types
32. How do you define a class in PHP?
Example:
class MyClass {
    // Properties
    public $property;
    
    // Methods
    public function myMethod() {
        // method code
    }
}
33. What is the difference between public, private, and protected?
  • public: Accessible from anywhere
  • private: Accessible only within the class
  • protected: Accessible within the class and its child classes
34. What is a constructor in PHP?
A constructor is a special method (__construct()) that is automatically called when an object is created. Example:
class MyClass {
    public function __construct() {
        echo "Object created";
    }
}
$obj = new MyClass(); // Outputs "Object created"
35. What is method chaining in PHP?
Method chaining allows calling multiple methods in a single statement by returning $this from each method. Example:
class Chainable {
    public function method1() {
        // code
        return $this;
    }
    public function method2() {
        // code
        return $this;
    }
}
$obj = new Chainable();
$obj->method1()->method2();
Forms and User Input
36. How do you retrieve form data submitted with GET method?
Use the $_GET superglobal: $value = $_GET['field_name'];
37. How do you retrieve form data submitted with POST method?
Use the $_POST superglobal: $value = $_POST['field_name'];
38. How do you check if a form has been submitted?
Example:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Form submitted
}
Or check for a specific submit button:
if(isset($_POST['submit'])) {
    // Form submitted
}
39. How do you prevent XSS attacks in PHP forms?
Use htmlspecialchars() to escape output:
echo htmlspecialchars($_POST['input'], ENT_QUOTES, 'UTF-8');
Also consider:
  • Input validation
  • Content Security Policy (CSP) headers
  • Using prepared statements for database queries
40. How do you upload a file in PHP?
Example:
<form method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>

<?php
if(isset($_FILES['file'])) {
    $target = "uploads/" . basename($_FILES['file']['name']);
    move_uploaded_file($_FILES['file']['tmp_name'], $target);
}
?>
Sessions and Cookies
41. How do you start a session in PHP?
Use session_start() at the beginning of your script:
<?php
session_start();
$_SESSION['user'] = "John";
?>
42. How do you destroy a session?
<?php
session_start();
session_unset(); // removes all session variables
session_destroy(); // destroys the session
?>
43. How do you set a cookie in PHP?
Use setcookie():
setcookie("name", "value", time()+3600, "/"); // expires in 1 hour
44. How do you retrieve a cookie value?
Use the $_COOKIE superglobal: $value = $_COOKIE['name'];
45. What is the difference between sessions and cookies?
  • Sessions are stored on the server, cookies on the client
  • Sessions are more secure as data isn't sent to the client
  • Cookies have size limits (typically 4KB), sessions don't
  • Cookies can persist after browser is closed, sessions typically don't
Database Interaction
46. How do you connect to a MySQL database in PHP?
Using mysqli:
$conn = new mysqli("hostname", "username", "password", "database");
if($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
Using PDO:
try {
    $conn = new PDO("mysql:host=hostname;dbname=database", "username", "password");
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}
47. What is the difference between mysqli and PDO?
  • PDO supports multiple databases, mysqli is MySQL-specific
  • PDO has named parameters in prepared statements
  • mysqli has some MySQL-specific features not in PDO
  • PDO has a consistent API across databases
48. How do you prevent SQL injection in PHP?
Use prepared statements:
  • With mysqli:
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
  • With PDO:
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = :email");
    $stmt->bindParam(':email', $email);
    $stmt->execute();
49. How do you fetch data from a MySQL database?
  • mysqli procedural:
    $result = mysqli_query($conn, "SELECT * FROM table");
    while($row = mysqli_fetch_assoc($result)) {
        echo $row['column'];
    }
  • mysqli object-oriented:
    $result = $conn->query("SELECT * FROM table");
    while($row = $result->fetch_assoc()) {
        echo $row['column'];
    }
  • PDO:
    $stmt = $conn->query("SELECT * FROM table");
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $row['column'];
    }
50. How do you insert data into a MySQL database?
Using prepared statements with mysqli:
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
With PDO:
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
Error Handling
51. How do you handle errors in PHP?
PHP provides several error handling methods:
  • Basic error handling with die(): if(!file) die("Error: File not found");
  • Custom error handlers with set_error_handler()
  • Exceptions with try-catch blocks
  • Error reporting configuration in php.ini
52. What is the difference between exceptions and errors?
  • Errors are problems that should not occur in normal operation (syntax errors, fatal errors)
  • Exceptions are exceptional conditions that can be caught and handled programmatically
  • Exceptions can be thrown and caught, errors typically can't
53. How do you create a custom exception handler?
Example:
function customExceptionHandler($exception) {
    echo "Custom handler: " . $exception->getMessage();
}
set_exception_handler('customExceptionHandler');

throw new Exception("Something went wrong");
54. What are the different error levels in PHP?
Common error levels:
  • E_ERROR: Fatal run-time errors
  • E_WARNING: Non-fatal run-time errors
  • E_PARSE: Compile-time parse errors
  • E_NOTICE: Run-time notices
  • E_STRICT: Suggestions for forward compatibility
  • E_ALL: All errors and warnings
55. How do you log errors to a file in PHP?
Configure in php.ini or use ini_set():
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');
Or use error_log() function:
error_log("Error message", 3, "/path/to/error.log");
File Handling
56. How do you read a file in PHP?
Several methods:
  • file_get_contents(): $content = file_get_contents("file.txt");
  • fopen() with fread():
    $file = fopen("file.txt", "r");
    $content = fread($file, filesize("file.txt"));
    fclose($file);
  • file(): $lines = file("file.txt"); (reads into array)
57. How do you write to a file in PHP?
Several methods:
  • file_put_contents(): file_put_contents("file.txt", $content);
  • fopen() with fwrite():
    $file = fopen("file.txt", "w");
    fwrite($file, $content);
    fclose($file);
58. How do you check if a file exists?
Use file_exists(): if(file_exists("file.txt")) { ... }
59. How do you delete a file in PHP?
Use unlink(): unlink("file.txt");
60. How do you get file information (size, type, etc.)?
Several functions:
  • filesize(): $size = filesize("file.txt");
  • filetype(): $type = filetype("file.txt");
  • pathinfo(): $info = pathinfo("file.txt");
  • finfo_file(): For MIME type detection
Security
61. How do you hash passwords in PHP?
Use password_hash() and password_verify():
// Hashing
$hash = password_hash($password, PASSWORD_DEFAULT);

// Verifying
if(password_verify($input_password, $hash)) {
    // Password correct
}
62. What is CSRF and how do you prevent it?
CSRF (Cross-Site Request Forgery) is an attack that tricks users into performing unwanted actions. Prevention methods:
  • Use CSRF tokens in forms
  • Check the Referer header
  • Implement SameSite cookies
  • Require re-authentication for sensitive actions
63. How do you sanitize user input in PHP?
Methods include:
  • filter_var(): $clean = filter_var($input, FILTER_SANITIZE_STRING);
  • htmlspecialchars() for output
  • Prepared statements for database queries
  • Regular expressions for pattern validation
64. What is SQL injection and how do you prevent it?
SQL injection is an attack where malicious SQL is inserted into queries. Prevention:
  • Always use prepared statements with parameterized queries
  • Use ORMs or query builders
  • Validate and sanitize all input
  • Follow the principle of least privilege for database users
65. How do you secure PHP sessions?
Session security measures:
  • Use session_regenerate_id() after login
  • Set session.cookie_httponly and session.cookie_secure in php.ini
  • Store sessions in a secure location
  • Set appropriate session timeouts
  • Validate session data
PHP Functions and Features
66. What are magic methods in PHP?
Magic methods are special methods that start with __. Common ones:
  • __construct(): Class constructor
  • __destruct(): Class destructor
  • __get(), __set(): Property access
  • __call(), __callStatic(): Method overloading
  • __toString(): Object to string conversion
67. What is autoloading in PHP?
Autoloading automatically loads class files when they're needed. Example with spl_autoload_register():
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});
68. What are traits in PHP?
Traits are a mechanism for code reuse in single inheritance languages. Example:
trait Loggable {
    public function log($msg) {
        echo $msg;
    }
}

class User {
    use Loggable;
}

$user = new User();
$user->log("Message");
69. What are generators in PHP?
Generators provide an easy way to implement iterators without creating a class. Example:
function xrange($start, $end) {
    for($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

foreach(xrange(1, 10) as $num) {
    echo $num;
}
70. What are namespaces in PHP?
Namespaces prevent name collisions between code. Example:
namespace MyProject;

class MyClass {
    // class code
}

$obj = new \MyProject\MyClass();
PHP and Web Services
71. How do you make a GET request in PHP?
Using file_get_contents():
$response = file_get_contents('http://example.com/api?param=value');
Using cURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api?param=value');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
72. How do you make a POST request in PHP?
Using file_get_contents():
$options = [
    'http' => [
        'method' => 'POST',
        'content' => http_build_query(['key' => 'value'])
    ]
];
$context = stream_context_create($options);
$response = file_get_contents('http://example.com/api', false, $context);
Using cURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['key' => 'value']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
73. How do you parse JSON in PHP?
Use json_decode():
$json = '{"name":"John","age":30}';
$data = json_decode($json);
echo $data->name; // John
For associative arrays:
$data = json_decode($json, true);
echo $data['name']; // John
74. How do you create a REST API in PHP?
Basic example:
header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", trim($_SERVER['PATH_INFO'],'/'));

switch($method) {
    case 'GET':
        // Handle GET request
        echo json_encode(["message" => "GET response"]);
        break;
    case 'POST':
        // Handle POST request
        $input = json_decode(file_get_contents('php://input'), true);
        echo json_encode(["received" => $input]);
        break;
    // Other methods...
}
75. How do you handle CORS in PHP?
Set appropriate headers:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
For preflight requests:
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("HTTP/1.1 200 OK");
    exit();
}
Performance and Optimization
76. How do you optimize PHP performance?
Optimization techniques:
  • Use OPcache (opcode caching)
  • Optimize database queries and use indexing
  • Minimize file operations
  • Use efficient data structures and algorithms
  • Implement caching (APCu, Redis, Memcached)
  • Use a PHP accelerator
  • Profile code with Xdebug
77. What is OPcache and how does it work?
OPcache improves PHP performance by storing precompiled script bytecode in shared memory, eliminating the need for PHP to load and parse scripts on each request. Enable in php.ini:
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
78. How do you profile PHP code?
Use tools like:
  • Xdebug with KCacheGrind or QCacheGrind
  • Blackfire.io
  • New Relic
  • Built-in microtime() for simple profiling
79. What are some common PHP performance bottlenecks?
Common bottlenecks:
  • Inefficient database queries
  • Excessive file operations
  • Memory leaks
  • Unoptimized loops
  • Unnecessary object instantiation
  • Large arrays or data structures
  • Network calls
80. How do you implement caching in PHP?
Caching methods:
  • OPcache for bytecode caching
  • APCu for user data caching
  • Memcached or Redis for distributed caching
  • File-based caching
  • HTTP caching headers
  • Varnish or other reverse proxy caching
PHP Frameworks
81. What are some popular PHP frameworks?
Popular PHP frameworks:
  • Laravel
  • Symfony
  • CodeIgniter
  • Zend Framework / Laminas
  • CakePHP
  • Yii
  • Phalcon
  • Slim (micro-framework)
82. What is Composer and how is it used?
Composer is a dependency manager for PHP. Usage:
  • Install packages: composer require package/name
  • Autoloading: require 'vendor/autoload.php';
  • Manage dependencies in composer.json
83. What is MVC and how is it implemented in PHP?
MVC (Model-View-Controller) is an architectural pattern:
  • Model: Handles data and business logic
  • View: Handles presentation and user interface
  • Controller: Handles user input and coordinates model/view
Example in PHP frameworks like Laravel or CodeIgniter.
84. What are some advantages of using a PHP framework?
Advantages:
  • Faster development
  • Code organization and structure
  • Built-in security features
  • Community support
  • Reusable components
  • Following best practices
  • Database abstraction
85. What is Laravel and what are its key features?
Laravel is a popular PHP framework with features:
  • Eloquent ORM
  • Blade templating engine
  • Artisan command-line tool
  • Middleware
  • Authentication system
  • Routing
  • Migrations
  • Testing support
Advanced PHP Concepts
86. What are PHP closures?
Closures are anonymous functions that can access variables from the parent scope. Example:
$message = 'hello';
$closure = function() use ($message) {
    echo $message;
};
$closure(); // outputs "hello"
87. What is dependency injection in PHP?
Dependency injection is a technique where dependencies are "injected" into a class rather than created within it. Example:
class Logger {
    public function log($message) { /* ... */ }
}

class UserService {
    private $logger;
    
    public function __construct(Logger $logger) {
        $this->logger = $logger;
    }
    
    public function createUser() {
        $this->logger->log("User created");
    }
}

$logger = new Logger();
$userService = new UserService($logger);
88. What are PHP attributes (annotations)?
Attributes (introduced in PHP 8) provide structured metadata. Example:
#[Route("/api/posts", methods: ["GET"])]
class PostController {
    #[ORM\Column(type: "string")]
    public $title;
}
89. What is type hinting in PHP?
Type hinting allows specifying expected types for parameters and return values. Example:
function addNumbers(int $a, int $b): int {
    return $a + $b;
}
90. What are PHP enums?
Enums (introduced in PHP 8.1) are a special kind of class for enumerations. Example:
enum Status {
    case DRAFT;
    case PUBLISHED;
    case ARCHIVED;
}

$status = Status::PUBLISHED;
PHP 8 Features
91. What are some key features of PHP 8?
PHP 8 features:
  • Just-In-Time (JIT) compilation
  • Named arguments
  • Attributes (annotations)
  • Union types
  • Match expression
  • Constructor property promotion
  • Nullsafe operator
  • Stringable interface
  • New str_contains() function
92. What is the nullsafe operator in PHP 8?
The nullsafe operator (?->) short-circuits if the left-hand operand is null. Example:
// Instead of:
$country = $user?->getAddress()?->getCountry();

// Old way:
$country = null;
if($user !== null) {
    $address = $user->getAddress();
    if($address !== null) {
        $country = $address->getCountry();
    }
}
93. What are named arguments in PHP 8?
Named arguments allow passing arguments by parameter name. Example:
function createUser($name, $age, $email) { /* ... */ }

// Using named arguments:
createUser(age: 30, email: 'test@example.com', name: 'John');
94. What is the match expression in PHP 8?
The match expression is a more powerful switch alternative. Example:
$result = match($statusCode) {
    200, 201 => 'success',
    404 => 'not found',
    500 => 'server error',
    default => 'unknown status',
};
95. What is constructor property promotion in PHP 8?
Constructor property promotion simplifies property declaration. Example:
// Before:
class User {
    private string $name;
    private int $age;
    
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

// With property promotion:
class User {
    public function __construct(
        private string $name,
        private int $age
    ) {}
}
Miscellaneous
96. How do you debug PHP code?
Debugging methods:
  • var_dump(), print_r() for quick inspection
  • error_log() for logging
  • Xdebug for step debugging
  • PHP's built-in web server with error reporting
  • IDE debuggers
  • Tracing with debug_backtrace()
97. How do you implement internationalization in PHP?
Internationalization methods:
  • gettext extension
  • Locale-aware number/date formatting
  • UTF-8 support
  • Storing translations in arrays or databases
  • Using frameworks' i18n features
98. How do you work with dates and times in PHP?
Use the DateTime class:
$date = new DateTime('now');
echo $date->format('Y-m-d H:i:s');

// Date arithmetic
$date->add(new DateInterval('P10D')); // Add 10 days

// Timezone handling
$date = new DateTime('now', new DateTimeZone('America/New_York'));
99. How do you create a cron job in PHP?
Create a PHP script and set up a cron entry:
# Edit crontab with: crontab -e
# Run script every day at 2am
0 2 * * * /usr/bin/php /path/to/script.php
100. What are PHP standards recommendations (PSR)?
PSRs are standards by PHP-FIG (Framework Interop Group):
  • PSR-1: Basic coding standard
  • PSR-4: Autoloading standard
  • PSR-7: HTTP message interfaces
  • PSR-12: Extended coding style guide
  • PSR-15: HTTP handlers
They promote interoperability between PHP frameworks and libraries.

No comments:

Post a Comment

Fiverr Fee Calculator – Know What You Really Earn or Pay!

Fiverr Fee Calculator – Know What You Really Earn or Pay! 💸 "How much will I actually earn after Fiverr takes its cut?...