PHP Questions
Sharpen your PHP skills with the most asked syntax, arrays, and web dev questions.
1 What does PHP stand for and what is its main purpose?
What does PHP stand for and what is its main purpose?
PHP Overview
PHP is a server-side scripting language designed primarily for web development. The acronym PHP stands for Hypertext Preprocessor, which is a recursive acronym reflecting its capability to embed dynamic content into HTML pages.
Main Purpose of PHP
The primary purpose of PHP is to generate dynamic web content and handle server-side operations. PHP scripts are executed on the server, producing HTML that is sent to the client's browser. This allows developers to build interactive, database-driven websites and applications.
- Dynamic Web Pages: PHP allows content to change dynamically based on user input, session data, or database queries.
- Server-Side Processing: PHP can perform backend tasks like form processing, file handling, and session management.
- Database Interaction: PHP has native support for connecting to databases such as MySQL, PostgreSQL, and SQLite, making it ideal for data-driven applications.
- Integration with HTML/CSS/JS: PHP code can be embedded directly into HTML, allowing seamless integration with front-end technologies.
- Open-Source and Cross-Platform: PHP is free to use and runs on multiple platforms including Windows, Linux, and macOS.
Key Features
- Interpreted language — no compilation needed, scripts run directly on the server.
- Supports a wide range of databases and protocols.
- Rich set of built-in functions and libraries for web development.
- Supports object-oriented programming as well as procedural coding styles.
- Extensible via third-party libraries and frameworks like Laravel, Symfony, and CodeIgniter.
Example Usage
<?php
// Display current date and time
echo 'Today is ' . date('l, F j, Y');
?>In this example, PHP dynamically generates and displays the current date when the page is accessed.
Summary
In short, PHP is a versatile server-side language designed to create dynamic web applications. Its main purpose is to enable developers to generate dynamic content, interact with databases, manage user sessions, and build interactive and efficient web applications.
2 What are the common uses of PHP?
What are the common uses of PHP?
Overview of PHP Uses
PHP is a versatile scripting language primarily used for server-side web development. It can handle various backend tasks that enable websites and applications to be dynamic, interactive, and database-driven.
Common Uses
- Server-Side Scripting: PHP is executed on the server, generating dynamic content before sending HTML to the browser.
- Form Handling: PHP can process user input from HTML forms, validate data, and store it in databases.
- Database Interaction: PHP integrates with databases like MySQL, PostgreSQL, and SQLite to store, retrieve, and manipulate data.
- Session Management: PHP manages user sessions using cookies or session variables to maintain login states and preferences.
- REST API Development: PHP frameworks like Laravel or Slim enable building APIs for web and mobile applications.
- Dynamic Web Pages: PHP generates HTML, JSON, or XML dynamically based on user input, database queries, or other server-side logic.
Example
<?php
$name = $_POST['name'] ?? 'Guest';
echo 'Hello, ' . htmlspecialchars($name);
?>This script handles form input and outputs a dynamic greeting.
Summary
In short, PHP's main uses revolve around building dynamic, interactive web applications, managing server-side logic, and integrating with databases and APIs.
3 How do you execute a PHP script from the command line?
How do you execute a PHP script from the command line?
Executing PHP from CLI
PHP can be executed from the command line interface (CLI) without a web server. This is useful for running background tasks, automation scripts, cron jobs, or testing scripts quickly.
Steps to Run PHP Script via CLI
- Open a terminal or command prompt.
- Navigate to the directory containing the PHP script.
- Run the script using:
php script.php
Example
<?php
// hello.php
echo 'Hello, CLI World!';
?>Command:
php hello.phpOutput:
Hello, CLI World!Benefits
- Automates tasks like backups or data processing.
- Runs scripts faster than web server execution in some cases.
- Useful for testing and debugging PHP code without a browser.
4 What are the differences between PHP 5 and PHP 7/8?
What are the differences between PHP 5 and PHP 7/8?
Overview
PHP has evolved significantly from version 5 to versions 7 and 8, with major performance improvements, enhanced type support, and new language features.
Key Differences
- Performance: PHP 7 introduced Zend Engine 3.0 with double speed improvements and reduced memory usage compared to PHP 5.
- Error Handling: PHP 7/8 replaced many fatal errors with exceptions, allowing better error control using try/catch blocks.
- Type Declarations: PHP 7/8 added scalar type hints, return type hints, and PHP 8 introduced union types.
- New Features in PHP 8: JIT compilation for performance, attributes for metadata, named arguments, match expressions, and nullsafe operator.
- Backward Compatibility: Some deprecated functions and features in PHP 5 were removed or improved in PHP 7/8.
- Security and Standards: PHP 7/8 improved cryptography, password hashing, and type safety compared to PHP 5.
Summary
Overall, PHP 7 and 8 offer faster execution, better error handling, enhanced type system, and modern language constructs. PHP 5 is outdated and less secure and should be avoided for new projects.
5 What are the common ways to embed PHP into HTML?
What are the common ways to embed PHP into HTML?
Embedding PHP in HTML
PHP is often embedded directly into HTML to create dynamic web pages. PHP scripts execute on the server and generate HTML that is sent to the browser.
Methods to Embed PHP
- Standard PHP tags:
<?php ... ?>are the most common and portable way to embed PHP code. - Short echo tags:
<?= ... ?>are shorthand for<?php echo ... ?>and used for quickly outputting values. - ASP-style tags (deprecated in many setups):
<% ... %> - Script tags (rarely used):
<script language="php"> ... </script>
Example
<!DOCTYPE html>
<html>
<body>
<h1>Welcome</h1>
<?php
$name = 'John';
echo '<p>Hello, ' . $name . '</p>';
?>
</body>
</html>Benefits
- Allows dynamic content generation alongside static HTML.
- Easy integration with databases and user input.
- Supports reusable templates and modular PHP components.
6 How do you declare a PHP variable and what are variable scope types?
How do you declare a PHP variable and what are variable scope types?
Declaring Variables in PHP
In PHP, variables are declared using the $ symbol followed by the variable name. Variable names are case-sensitive and must start with a letter or underscore, followed by letters, numbers, or underscores.
Example:
$name = 'John';
$age = 25;
$price = 19.99;Variable Scopes in PHP
- Local scope: Variables declared inside a function and accessible only within that function.
- Global scope: Variables declared outside functions. To access them inside a function, use
global $var;or$GLOBALS['var']. - Static scope: Variables declared with
staticinside a function retain their value between function calls. - Function parameters: Variables passed into a function are local to that function.
Example of variable scopes:
$count = 10; // global
function testScope($param) {
static $callCount = 0; // retains value
$callCount++;
global $count;
echo "Global count: $count, Call count: $callCount, Param: $param";
} 7 What data types does PHP support?
What data types does PHP support?
PHP Data Types Overview
PHP supports various data types that allow you to store different kinds of values:
- Scalar types: integer, float (double), string, boolean.
- Compound types: array, object.
- Special types: NULL (represents no value), resource (external resource like file handle or database connection).
- Callable: a reference to a function or method that can be executed.
- Iterable: a type that can be looped over with
foreach.
Example:
$name = 'Alice'; // string
$age = 30; // integer
$price = 19.99; // float
$isActive = true; // boolean
$colors = ['red','green','blue']; // array
$person = new stdClass(); // object
$resource = fopen('file.txt','r'); // resource
$nothing = null; // NULL 8 How does PHP handle error reporting?
How does PHP handle error reporting?
PHP Error Handling Overview
PHP provides multiple mechanisms for reporting and handling errors, including notices, warnings, and fatal errors. Modern PHP also supports exceptions for structured error handling.
Controlling Error Reporting
- php.ini settings:
error_reportingdisplay_errorslog_errorscontrol what errors are shown or logged. - Runtime functions: Use
error_reporting(E_ALL);to set reporting level orini_set('display_errors', 1);to display errors. - Custom error handlers:
set_error_handler()allows you to define your own error handling logic. - Exceptions: PHP 7+ encourages throwing and catching exceptions using
try/catchblocks.
Example:
ini_set('display_errors', 1);
error_reporting(E_ALL);
try {
if (!file_exists('data.txt')) {
throw new Exception('File not found');
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} 9 What is the purpose of the php.ini file?
What is the purpose of the php.ini file?
php.ini Overview
The php.ini file is PHP's main configuration file. It controls various aspects of PHP's runtime behavior and server integration.
Common Configurations in php.ini
- Error reporting:
error_reportingdisplay_errorslog_errors - Resource limits:
memory_limitmax_execution_timepost_max_sizeupload_max_filesize - Session settings:
session.save_pathsession.gc_maxlifetime - Extensions: Load required PHP extensions like MySQL, GD, or cURL.
- Security settings:
disable_functionsopen_basedirexpose_php
Example:
[PHP]
max_execution_time = 30
memory_limit = 128M
display_errors = On
error_reporting = E_ALLThis ensures PHP scripts have sufficient memory, controlled execution time, and proper error visibility.
10 How do you define a constant in PHP?
How do you define a constant in PHP?
Defining Constants in PHP
Constants are immutable values in PHP. Once defined, their values cannot be changed during script execution.
Methods to Define Constants
- Using define():
define('NAME', 'value');— works globally in the script. - Using const:
const NAME = 'value';— often used inside classes and must be known at compile time.
Example:
define('SITE_NAME', 'MyWebsite');
echo SITE_NAME; // Outputs 'MyWebsite'
class App {
const VERSION = '1.0';
}
echo App::VERSION; // Outputs '1.0'Key Points: Constants are case-sensitive by default (unless define('NAME', 'value', true) is used for case-insensitive). They are useful for configuration values, fixed strings, and global flags.
11 Can you describe the lifecycle of a PHP request?
Can you describe the lifecycle of a PHP request?
PHP Request Lifecycle Overview
The lifecycle of a PHP request describes the steps taken from the moment a client requests a PHP page until the response is delivered back to the client. Understanding this helps in optimizing performance and debugging issues.
Step 1: Client Request
A user or client (browser, mobile app, or API consumer) sends an HTTP request to the web server asking for a PHP resource.
Step 2: Web Server Handling
The web server (e.g., Apache, Nginx) identifies the request as a PHP script and passes it to the PHP interpreter via modules like mod_php, PHP-FPM, or FastCGI.
Step 3: PHP Script Execution
- PHP reads the script and interprets the code.
- It processes superglobals such as
$_GET$_POST$_COOKIEand$_SESSION. - Business logic executes, which may include database queries, API calls, file operations, and computations.
Step 4: Generating Output
The PHP script produces output, usually HTML, JSON, or XML. Output buffering can be used to manage content before sending it to the client.
Step 5: Response Sent
The web server sends the generated output back to the client as an HTTP response.
Step 6: Cleanup
PHP cleans up memory, closes database connections, and releases resources used during script execution. Session data is persisted if applicable.
12 What is a session in PHP, and how do the session_start() and session_destroy() functions work?
What is a session in PHP, and how do the session_start() and session_destroy() functions work?
Understanding Sessions in PHP
Sessions in PHP allow you to store user-specific information on the server to maintain state across multiple HTTP requests. This is crucial for features like login systems, shopping carts, and user preferences.
Starting a Session
The session_start() function initializes a new session or resumes an existing session based on the session ID provided by the client (usually in a cookie called PHPSESSID).
Example:
session_start();
$_SESSION['username'] = 'Alice';
$_SESSION['role'] = 'admin';This stores 'Alice' and 'admin' in the session, accessible across multiple pages.
Destroying a Session
The session_destroy() function ends the session, deletes all session data on the server, but does not unset the $_SESSION variable itself. It is often used during logout.
Example:
session_start();
session_destroy(); // Deletes all session data
Sessions are essential for stateful interactions in a stateless HTTP environment.
13 How does PHP support cookies?
How does PHP support cookies?
Working with Cookies in PHP
Cookies are small pieces of data stored on the client-side and sent back to the server with each request. They are commonly used for user tracking, preferences, and session management.
Setting a Cookie
Use setcookie() to create a cookie. It should be called before any output is sent to the browser.
Example:
setcookie('username', 'Alice', time() + 3600, '/'); // Expires in 1 hourAccessing Cookies
Use the $_COOKIE superglobal to read cookie values in subsequent requests.
if(isset($_COOKIE['username'])) {
echo 'Welcome ' . $_COOKIE['username'];
}Deleting a Cookie
To delete a cookie, set its expiration time in the past:
setcookie('username', '', time() - 3600, '/');Cookies help maintain client-side state while sessions store server-side state.
14 What is the difference between static and dynamic websites?
What is the difference between static and dynamic websites?
Static vs Dynamic Websites
Understanding the difference helps in selecting the appropriate approach for web development.
Static Websites
- Content is fixed and does not change unless manually edited.
- Built using HTML, CSS, and sometimes client-side JavaScript.
- Faster to load since no server-side processing is needed.
- Example: Personal portfolio, brochure sites.
Dynamic Websites
- Content is generated on-the-fly using server-side scripting languages like PHP, Python, or Node.js.
- Can interact with databases, APIs, and user input.
- Supports sessions, login systems, and personalized content.
- Example: E-commerce sites, social media platforms.
PHP is widely used to create dynamic websites by embedding logic within HTML pages, allowing content to change based on data or user interactions.
15 What is PEAR (the PHP Extension and Application Repository)?
What is PEAR (the PHP Extension and Application Repository)?
Understanding PEAR in PHP
PEAR stands for PHP Extension and Application Repository. It is a framework and package management system that allows developers to easily share and reuse PHP code.
Key Features:
- Provides a structured library of reusable PHP components for common tasks such as authentication, database access, and email handling.
- Includes a command-line tool to install, update, and manage packages.
- Encourages adherence to coding standards and best practices.
Example:
pear install Mail // Installs the PEAR Mail package
require_once 'Mail.php';
$mailer = Mail::factory('smtp', $params);PEAR simplifies code reuse and helps developers avoid reinventing common functionality in PHP applications.
16 What are some popular PHP frameworks?
What are some popular PHP frameworks?
Popular PHP Frameworks Overview
PHP frameworks provide reusable components and a structure to speed up web development while promoting best practices.
Laravel
- Modern, feature-rich framework.
- Offers routing, Eloquent ORM, authentication, and templating with Blade.
Symfony
- Highly configurable and reusable components.
- Widely used for enterprise applications.
CodeIgniter
- Lightweight, simple, and easy to learn.
- Minimal configuration and fast performance.
Zend Framework / Laminas
- Enterprise-ready, modular framework.
- Supports MVC and extensive components for building complex apps.
Yii
- High-performance framework with Gii code generator.
- Good for rapid development and CRUD-based applications.
Using a framework saves development time, enforces best practices, and makes applications easier to maintain and scale.
17 What are the different data (or variable) types available in PHP?
What are the different data (or variable) types available in PHP?
PHP Variable Types
PHP supports several data types, categorized as follows:
1. Scalar Types
- Integer — Whole numbers, e.g., 42.
- Float / Double — Decimal numbers, e.g., 3.14.
- String — Sequence of characters, e.g., 'Hello'.
- Boolean — true or false values.
2. Compound Types
- Array — Stores multiple values, can be indexed or associative.
- Object — Instances of classes containing properties and methods.
3. Special Types
- NULL — Represents a variable with no value.
- Resource — References external resources like database connections or file handles.
4. Additional Type Declarations
- Callable — Represents a function or method that can be called.
- Iterable — Represents any array or object implementing Traversable.
Proper use of data types ensures predictable behavior and reduces bugs in PHP applications.
18 Is PHP a case-sensitive language?
Is PHP a case-sensitive language?
Case Sensitivity in PHP
Understanding case sensitivity is important to avoid unexpected behavior in PHP scripts.
Variables
Variable names in PHP are case-sensitive. For example:
$name = 'Alice';
$Name = 'Bob';
echo $name; // Outputs: Alice
echo $Name; // Outputs: BobFunctions and Keywords
Function names, class names, and PHP keywords are not case-sensitive:
function greet() { echo 'Hello'; }
GREET(); // Works fine
ECHO 'Test'; // Works fineConstants
By default, user-defined constants are case-sensitive unless explicitly defined otherwise.
Being mindful of case sensitivity prevents variable collisions and makes code more maintainable.
19 What is the echo construct in PHP and how does it differ from print?
What is the echo construct in PHP and how does it differ from print?
Echo vs Print in PHP
Both echo and print are used to output data in PHP, but there are subtle differences:
Echo
- A language construct, not a function, used to output one or more strings.
- Faster than
printbecause it does not return a value. - Multiple parameters can be used (though rarely done):
echo 'Hello', ' World';
- Also a language construct, but behaves like a function that returns 1.
- Can output only one argument at a time.
- Return value allows it to be used in expressions:
$result = print 'Hello';
In practice, echo is preferred for most outputs due to its speed and flexibility.
20 What are the rules for determining the “truthiness” of a value in PHP?
What are the rules for determining the “truthiness” of a value in PHP?
Truthiness in PHP
PHP evaluates certain values as true or false when used in boolean contexts like if statements.
Values Considered False:
false(boolean false)0(integer zero)0.0(float zero)- Empty string
''or string'0' NULL- Empty array
[]
Values Considered True:
All other values, including non-empty strings, non-zero numbers, and non-empty arrays, are considered true.
Example:
$value = '0';
if ($value) {
echo 'True';
} else {
echo 'False'; // Outputs 'False'
}Understanding truthiness helps prevent logic errors, especially when dealing with user input, form validation, and conditional statements.
21 Explain late static binding in PHP.
Explain late static binding in PHP.
Late Static Binding (LSB)
Late static binding in PHP allows static references inside class methods to refer to the class that was actually called at runtime rather than the class where the method is defined.
This is especially useful in inheritance hierarchies where a method defined in a parent class needs to reference the calling child class.
How it works:
- The
self::keyword refers to the class where the method is defined (early binding). - The
static::keyword uses late static binding to refer to the class that was actually called.
Example:
class ParentClass {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Late static binding
}
}
class ChildClass extends ParentClass {
public static function who() {
echo __CLASS__;
}
}
ChildClass::test(); // Outputs 'ChildClass'Without static::self::who() would output 'ParentClass'. LSB enables more flexible and dynamic code reuse.
22 What is a namespace in PHP and why are namespaces used?
What is a namespace in PHP and why are namespaces used?
Namespaces in PHP
Namespaces allow developers to encapsulate classes, interfaces, functions, and constants under a unique name to avoid naming conflicts.
They are particularly useful when integrating third-party libraries or large codebases where multiple components might share the same class names.
Syntax:
namespace MyAppModels;
class User {
// class code
}To use this class in another namespace or file, you can import it using use:
use MyAppModelsUser;
$user = new User();Namespaces promote modular, organized code and prevent collisions between similarly named classes or functions in different libraries.
23 What is a closure (anonymous function) in PHP, and how do you use it?
What is a closure (anonymous function) in PHP, and how do you use it?
Closures in PHP
A closure is an anonymous function that can be assigned to a variable, passed as an argument, or returned from another function. Closures can also capture variables from the surrounding scope using the use keyword.
Example:
$factor = 2;
$multiply = function($x) use ($factor) {
return $x * $factor;
};
echo $multiply(5); // Outputs 10Closures are widely used for callbacks in array functions (array_maparray_filter), event handlers, or when you need small, inline functions without creating a full named function.
24 Explain the concept of traits in PHP and how they are used.
Explain the concept of traits in PHP and how they are used.
Traits in PHP
Traits provide a mechanism to share methods between classes without using inheritance. This allows developers to reuse code across unrelated classes.
Defining a Trait:
trait Logger {
public function log($message) {
echo "Log: $message";
}
}Using a Trait in a Class:
class User {
use Logger;
}
$user = new User();
$user->log('User created'); // Outputs 'Log: User created'Traits can include multiple methods, and classes can use multiple traits. They help reduce code duplication while avoiding the limitations of single inheritance.
25 How does PHP handle exceptions and error handling?
How does PHP handle exceptions and error handling?
Error Handling and Exceptions in PHP
PHP provides a structured mechanism for handling runtime errors using exceptions, which can be caught and managed to prevent application crashes.
Basic Syntax:
try {
// Code that may throw an exception
if (!file_exists('data.txt')) {
throw new Exception('File not found');
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} finally {
echo 'Execution finished';
}Key Points:
try— Wraps code that might throw an exception.catch— Catches thrown exceptions and allows handling.finally— Executes code regardless of exceptions, often used for cleanup.- Custom exception classes can extend
Exceptionto handle domain-specific errors.
Using exceptions instead of error codes improves code readability, makes debugging easier, and allows centralized error handling strategies.
26 What are type declarations and return types in PHP 7/8?
What are type declarations and return types in PHP 7/8?
Type Declarations and Return Types
PHP 7 and 8 introduced type declarations that allow developers to specify expected types for function parameters and return values. This helps catch type errors early and improves code readability and maintainability.
Supported types include:
- Scalar types:
intfloatstringbool - Compound types:
arrayobject - Callable types:
callable - Class/interface types
- Union types (PHP 8+): allows multiple accepted types, e.g.,
int|string
Example:
function add(int $a, int $b): int {
return $a + $b;
}If the passed arguments or return value do not match the declared types, a TypeError is thrown.
27 What is a generator in PHP and when would you use one?
What is a generator in PHP and when would you use one?
Generators in PHP
Generators provide a way to iterate over data without creating a complete array in memory. This is achieved using the yield keyword.
Generators are ideal for:
- Processing large datasets.
- Streaming data from files or APIs.
- Reducing memory usage in loops.
Example:
function numbers($max) {
for ($i = 1; $i <= $max; $i++) {
yield $i;
}
}
foreach (numbers(5) as $n) {
echo $n . ' '; // Outputs: 1 2 3 4 5
} 28 What are anonymous classes in PHP 7/8 and how do you use them?
What are anonymous classes in PHP 7/8 and how do you use them?
Anonymous Classes in PHP
Anonymous classes are classes without a name and are often used for quick object creation, simple implementations of interfaces, or short-lived objects.
Example:
$logger = new class {
public function log($msg) {
echo "Log: $msg";
}
};
$logger->log('Test message'); // Outputs: Log: Test messageAnonymous classes reduce boilerplate when you do not need a fully named class for a single use case.
29 How is the yield keyword used in PHP?
How is the yield keyword used in PHP?
The yield Keyword
The yield keyword allows a function to return values one at a time while maintaining the state of the function. This avoids building a full array in memory.
Usage:
function letters() {
yield 'A';
yield 'B';
yield 'C';
}
foreach (letters() as $letter) {
echo $letter . ' '; // Outputs: A B C
}Each yield pauses the function, resuming from the same point on the next iteration, making it memory-efficient.
30 Describe the difference between include, include_once, require, and require_once in PHP.
Describe the difference between include, include_once, require, and require_once in PHP.
Include vs Require in PHP
PHP provides four functions to include files:
| Function | Behavior |
|---|---|
include | Includes a file; gives a warning if file not found, but script continues. |
require | Includes a file; gives a fatal error if file not found, stopping script execution. |
include_once | Same as include, but ensures the file is included only once, preventing redeclaration errors. |
require_once | Same as require, but ensures the file is included only once. |
Use require when the file is essential for execution, and include when failure should not stop the script. The _once versions are useful for preventing multiple inclusions.
31 What are PHP superglobals and can you list some of them?
What are PHP superglobals and can you list some of them?
PHP Superglobals Overview
Superglobals are special built-in variables in PHP that are always accessible, regardless of scope. You do not need to use global to access them inside functions or classes.
They provide information about user input, server environment, session data, and more. Some of the most commonly used superglobals include:
$_GET— collects data sent via URL query string.$_POST— collects data sent in HTTP POST requests.$_REQUEST— combines$_GET$_POST, and$_COOKIEdata.$_SERVER— contains server and execution environment info like$_SERVER['HTTP_HOST']or$_SERVER['REQUEST_METHOD'].$_COOKIE— stores cookie data sent by clients.$_SESSION— stores session-specific data on the server.$_FILES— holds uploaded file information.$_ENV— contains environment variables.$GLOBALS— references all global variables in the script.
Superglobals are essential for handling requests, user sessions, file uploads, and environment-specific behavior.
32 What is the difference between $_GET and $_POST?
What is the difference between $_GET and $_POST?
Difference between $_GET and $_POST
PHP provides $_GET and $_POST to retrieve user-submitted form data. Both are associative arrays, but they differ in how data is transmitted:
- $_GET: Sends data via the URL query string. Example:
page.php?name=John&age=30. Suitable for bookmarking and non-sensitive data. Limited in length by the URL size. - $_POST: Sends data in the HTTP request body. Used for sensitive data like passwords or file uploads. No strict size limit and not visible in the URL.
Example:
<form method='get' action='submit.php'>
<input name='name' />
<input type='submit' />
</form>
<form method='post' action='submit.php'>
<input name='password' type='password' />
<input type='submit' />
</form>Choosing the right method is important for security, data length, and usability.
33 What are PHP magic constants?
What are PHP magic constants?
PHP Magic Constants
Magic constants are built-in constants in PHP that provide information about the current script context. Their values change depending on where they are used, making them useful for debugging, logging, and dynamic behavior.
Common magic constants:
__LINE__— current line number in the script.__FILE__— full path and filename of the current file.__DIR__— directory of the current file.__FUNCTION__— name of the current function.__CLASS__— name of the current class.__METHOD__— name of the current class method.__NAMESPACE__— name of the current namespace.
Example usage:
echo 'File: ' . __FILE__ . ' on line ' . __LINE__;
function test() { echo __FUNCTION__; }Magic constants are invaluable for dynamic path management, logging, and debugging in PHP applications.
34 What are PHP magic methods?
What are PHP magic methods?
PHP Magic Methods
Magic methods are predefined methods with special behavior in PHP classes. They always begin with double underscores and allow customization of object behavior.
Some common magic methods:
__construct()— called when a new object is instantiated.__destruct()— called when an object is destroyed.__get($name)— triggered when reading inaccessible or undefined properties.__set($name, $value)— triggered when writing to inaccessible properties.__call($method, $args)— triggered when calling inaccessible methods.__toString()— returns a string representation of an object.
Example:
class Person {
private $data = [];
function __set($name, $value) { $this->data[$name] = $value; }
function __get($name) { return $this->data[$name] ?? null; }
}
$p = new Person();
$p->name = 'John';
echo $p->name; // Outputs: John 35 What is the difference between abstract classes and interfaces in PHP?
What is the difference between abstract classes and interfaces in PHP?
Abstract Classes vs Interfaces
Abstract classes and interfaces are tools for defining contracts in PHP, but they differ in flexibility and usage:
| Feature | Abstract Class | Interface |
|---|---|---|
| Methods | Can have abstract (no body) and concrete methods | Only method signatures, no implementation (PHP 8+ allows default methods) |
| Properties | Can contain properties with visibility | Cannot contain properties |
| Inheritance | A class can extend one abstract class | A class can implement multiple interfaces |
| Constructor | Can define a constructor | No constructor |
Example Abstract Class:
abstract class Animal {
abstract public function makeSound();
public function sleep() { echo 'Sleeping'; }
}Example Interface:
interface Movable {
public function move();
}Use abstract classes when sharing common code and interfaces for multiple implementations or contract enforcement.
36 What is the difference between public, private, and protected access modifiers in PHP?
What is the difference between public, private, and protected access modifiers in PHP?
Access Modifiers in PHP
Access modifiers control the visibility of properties and methods in PHP classes, defining where they can be accessed:
- Public: Members declared as public can be accessed from anywhere, including outside the class. This is the most permissive access level.
- Protected: Members declared as protected can only be accessed within the class itself and by subclasses (child classes). They are not accessible from outside the class hierarchy.
- Private: Members declared as private can only be accessed within the class where they are defined. Subclasses cannot access private members of the parent class.
Example:
class ParentClass {
public $publicVar = 'public';
protected $protectedVar = 'protected';
private $privateVar = 'private';
public function showVars() {
echo $this->publicVar . ', ' . $this->protectedVar . ', ' . $this->privateVar;
}
}
class ChildClass extends ParentClass {
public function showProtected() {
echo $this->protectedVar; // allowed
// echo $this->privateVar; // error
}
} 37 What is method overloading in PHP?
What is method overloading in PHP?
Method Overloading in PHP
Traditional method overloading (multiple methods with same name but different parameters) is not supported in PHP like in Java or C#. Instead, PHP provides magic methods for dynamic handling:
__call($name, $arguments)— invoked when calling inaccessible or undefined object methods.__callStatic($name, $arguments)— invoked when calling inaccessible or undefined static methods.
Example:
class Test {
public function __call($name, $args) {
echo "Called method '$name' with args: " . implode(', ', $args);
}
}
$obj = new Test();
$obj->hello('PHP', 2025); // dynamically handled by __callThis allows creating flexible APIs or handling method calls dynamically.
38 What is method overriding in PHP?
What is method overriding in PHP?
Method Overriding in PHP
Method overriding allows a subclass to provide a specific implementation of a method already defined in its parent class. This enables polymorphic behavior.
Rules:
- Method name must be the same.
- Visibility in the subclass cannot be more restrictive than the parent.
- Parameters and return types should match or be compatible.
Example:
class ParentClass {
public function greet() {
echo 'Hello from Parent';
}
}
class ChildClass extends ParentClass {
public function greet() {
echo 'Hello from Child';
}
}
$obj = new ChildClass();
$obj->greet(); // Outputs: Hello from Child 39 What is polymorphism in PHP?
What is polymorphism in PHP?
Polymorphism in PHP
Polymorphism is a core concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. It enables methods to perform differently depending on the object instance calling them.
PHP achieves polymorphism via:
- Inheritance — subclasses override or extend parent methods.
- Interfaces — different classes implement the same interface methods.
- Type hinting — accepting objects of the same parent class or interface.
Example using interface:
interface Shape {
public function draw();
}
class Circle implements Shape {
public function draw() { echo 'Drawing Circle'; }
}
class Square implements Shape {
public function draw() { echo 'Drawing Square'; }
}
function render(Shape $shape) {
$shape->draw();
}
render(new Circle()); // Drawing Circle
render(new Square()); // Drawing Square 40 What is the difference between == and === operators in PHP?
What is the difference between == and === operators in PHP?
Difference Between == and === in PHP
PHP provides two main comparison operators for equality:
==(Equal) — compares values after type conversion (type juggling). Example:0 == '0'is true.===(Identical) — compares both value and type. Example:0 === '0'is false because one is integer and the other is string.
Example:
var_dump(5 == '5'); // true
var_dump(5 === '5'); // false
var_dump(true == 1); // true
var_dump(true === 1); // falseUse === when strict type checking is required to prevent unexpected behavior from type coercion.
41 How do you connect PHP with MySQL?
How do you connect PHP with MySQL?
Connecting PHP with MySQL
PHP provides two main extensions for interacting with MySQL databases: mysqli and PDO.
Using mysqli (MySQL Improved)
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
echo 'Connected successfully';Using PDO (PHP Data Objects)
try {
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected successfully';
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}PDO provides a database-agnostic API, whereas mysqli is MySQL-specific.
42 What is the difference between mysqli and PDO in PHP?
What is the difference between mysqli and PDO in PHP?
mysqli vs PDO
Both are PHP extensions for database interaction, but they have differences:
| Feature | mysqli | PDO |
|---|---|---|
| Database Support | MySQL only | Supports MySQL, PostgreSQL, SQLite, Oracle, and others |
| API Style | Procedural & Object-Oriented | Object-Oriented only |
| Prepared Statements | Yes, MySQL only | Yes, works across supported databases |
| Flexibility | Limited to MySQL | Highly flexible, easier to switch databases |
43 What are prepared statements in PHP and why are they used?
What are prepared statements in PHP and why are they used?
Prepared Statements in PHP
Prepared statements are a way to execute SQL queries safely by separating query structure from data. They prevent SQL injection by binding parameters instead of directly concatenating user input.
Example using mysqli:
$stmt = $conn->prepare('SELECT * FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();Example using PDO:
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$rows = $stmt->fetchAll();Benefits:
- Prevents SQL injection
- Improves performance for repeated queries
- Cleaner and safer code
44 What is SQL injection and how can PHP prevent it?
What is SQL injection and how can PHP prevent it?
SQL Injection
SQL injection occurs when untrusted user input is directly included in SQL queries, allowing attackers to manipulate queries and access or modify the database.
Example of vulnerable code:
$query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "'";
$result = $conn->query($query);Safe alternative using prepared statements:
$stmt = $conn->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();Other prevention techniques include input validation and using PDO or mysqli with parameterized queries.
45 How do you sanitize user input in PHP?
How do you sanitize user input in PHP?
Sanitizing User Input
Sanitization ensures that input data is safe before using it in your application, preventing XSS, SQL injection, or other attacks.
Common PHP functions:
htmlspecialchars($input)— converts special characters to HTML entities.strip_tags($input)— removes HTML and PHP tags from input.filter_var($input, FILTER_SANITIZE_EMAIL)— removes illegal characters from email addresses.
Always combine sanitization with validation to ensure correct and safe input handling.
46 What is XSS (Cross-Site Scripting) and how do you prevent it in PHP?
What is XSS (Cross-Site Scripting) and how do you prevent it in PHP?
Cross-Site Scripting (XSS)
XSS is a security vulnerability where attackers inject malicious scripts (JavaScript, HTML) into web pages viewed by other users. This can steal cookies, perform actions on behalf of users, or manipulate content.
Prevention techniques:
- Escape output using
htmlspecialchars()or template engines. - Validate and sanitize user input.
- Use Content Security Policy (CSP) headers.
47 What is CSRF (Cross-Site Request Forgery) and how can PHP defend against it?
What is CSRF (Cross-Site Request Forgery) and how can PHP defend against it?
Cross-Site Request Forgery (CSRF)
CSRF is an attack that forces a logged-in user to unknowingly submit requests, performing actions they did not intend (like changing passwords or making transactions).
Prevention techniques in PHP:
- Generate unique CSRF tokens for forms.
- Validate the token on form submission.
- Use same-site cookies to restrict cross-origin requests.
- Check referer or origin headers where appropriate.
48 What are PHP sessions and how are they different from cookies?
What are PHP sessions and how are they different from cookies?
PHP Sessions vs Cookies
Sessions are server-side storage mechanisms that allow you to keep user-specific data across multiple requests. Each session is associated with a unique session ID, usually stored in a cookie or passed via URL. The data itself remains on the server, making sessions more secure for sensitive information like login credentials.
Cookies, on the other hand, store data directly in the user's browser and are sent with every HTTP request to the server. Cookies are limited in size and less secure since users can manipulate them.
Example usage:
session_start();
$_SESSION['username'] = 'John'; 49 How do you handle file uploads in PHP?
How do you handle file uploads in PHP?
Handling File Uploads in PHP
To handle file uploads, the HTML form must include enctype='multipart/form-data' and use method='POST'. The uploaded file is stored temporarily on the server and can be accessed through the $_FILES superglobal array.
Example:
<form action='upload.php' method='POST' enctype='multipart/form-data'>
<input type='file' name='fileToUpload' />
<input type='submit' value='Upload' />
</form>In PHP:
$targetDir = 'uploads/';
$targetFile = $targetDir . basename($_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $targetFile)) {
echo 'File uploaded successfully.';
} else {
echo 'File upload failed.';
} 50 What are file handling functions in PHP?
What are file handling functions in PHP?
File Handling Functions in PHP
PHP provides built-in functions to work with files on the server. These functions allow you to create, read, write, and manage files efficiently.
Common functions:
fopen()— Opens a file for reading, writing, or appending.fread()— Reads content from a file.fwrite()— Writes data to a file.fclose()— Closes a file pointer.file_get_contents()— Reads entire file content into a string.file_put_contents()— Writes data to a file.
51 What is the difference between unlink() and unset() in PHP?
What is the difference between unlink() and unset() in PHP?
unlink() vs unset()
unlink() deletes a file from the filesystem. Once executed, the file is permanently removed from the server.
unset() destroys a variable or array element in PHP memory. It does not affect files on the server; it simply removes the variable reference.
Example:
unlink('oldfile.txt'); // deletes file
$var = 'Hello';
unset($var); // destroys variable 52 What is the difference between require_once and include_once?
What is the difference between require_once and include_once?
require_once vs include_once
Both require_once and include_once ensure that a file is included only one time during script execution, preventing redeclaration errors.
Main differences:
| Function | Behavior on Failure |
|---|---|
| require_once | Throws a fatal error and stops script execution if the file is missing. |
| include_once | Emits a warning but allows script execution to continue if the file is missing. |
53 What are design patterns and which ones are common in PHP?
What are design patterns and which ones are common in PHP?
Design Patterns in PHP
Design patterns are proven, reusable solutions to common software design problems. They provide templates to structure code efficiently, improve maintainability, and encourage best practices.
Common PHP design patterns:
- Singleton: Ensures a class has only one instance and provides a global point of access.
- Factory: Creates objects without exposing the instantiation logic to the client.
- MVC (Model-View-Controller): Separates data, business logic, and presentation for better organization.
- Strategy: Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
- Observer: Allows objects to subscribe and receive updates when another object changes state.
- Dependency Injection: Injects dependencies into a class instead of creating them internally, improving testability and modularity.
54 What is dependency injection in PHP?
What is dependency injection in PHP?
Dependency Injection (DI) in PHP
Dependency Injection is a design pattern where a class receives its dependencies from external sources rather than instantiating them inside the class. This promotes loose coupling, making the code more modular, testable, and maintainable.
Example:
class Logger {
public function log($message) { echo $message; }
}
class UserService {
private $logger;
public function __construct(Logger $logger) {
$this->logger = $logger;
}
public function createUser($name) {
// create user logic
$this->logger->log('User created: ' . $name);
}
}
$logger = new Logger();
$service = new UserService($logger);
$service->createUser('John'); 55 What is an autoloader in PHP?
What is an autoloader in PHP?
Autoloaders in PHP
An autoloader is a mechanism that automatically loads class or interface files when they are instantiated, removing the need for multiple include or require statements. This simplifies code maintenance and improves readability.
PHP provides the spl_autoload_register() function to register one or more autoloader functions. When a class is used but not yet defined, PHP calls the registered autoloader to locate and include the file.
Example:
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.php';
});
$myObj = new MyClass(); // PHP automatically includes 'classes/MyClass.php' 56 What is Composer in PHP?
What is Composer in PHP?
Composer in PHP
Composer is the de facto dependency manager for PHP projects. It allows developers to define project dependencies in a composer.json file and automatically installs, updates, or removes packages from Packagist, the PHP package repository.
Composer also provides an autoloader for classes in installed packages, simplifying integration with third-party libraries and ensuring consistent project environments across different machines.
Example:
composer require monolog/monolog
// This installs the Monolog library and generates an autoloader 57 What is PSR in PHP?
What is PSR in PHP?
PSR (PHP Standards Recommendations)
PSRs are a set of coding standards and recommendations created by the PHP Framework Interop Group (PHP-FIG) to improve code interoperability and maintainability across PHP projects.
Some important PSRs:
- PSR-1: Basic coding standard including naming conventions and file structure.
- PSR-4: Autoloading standard for classes and namespaces.
- PSR-7: HTTP message interfaces for requests and responses.
- PSR-12: Extended coding style guide for consistent code formatting.
58 What are PHP streams?
What are PHP streams?
PHP Streams
Streams provide a consistent interface to read from and write to various data sources, including files, network sockets, and in-memory buffers. They allow you to treat different types of I/O in the same way using functions like fopen()fread(), and stream_get_contents().
Example:
$handle = fopen('example.txt', 'r');
$content = fread($handle, filesize('example.txt'));
fclose($handle);
echo $content; 59 What are PHP filters?
What are PHP filters?
PHP Filters
PHP provides a filter extension to validate and sanitize user input. This helps prevent common security issues like XSS or invalid input values. Filters can be applied to variables using functions like filter_var() or filter_input().
Example:
$email = 'test@example.com';
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Valid email';
} else {
echo 'Invalid email';
} 60 What are PHP stream contexts?
What are PHP stream contexts?
PHP Stream Contexts
Stream contexts provide a way to modify the behavior of streams by setting options and parameters. For example, you can specify HTTP headers, timeout settings, proxy information, or SSL options when accessing network resources.
They are created using stream_context_create() and passed to functions like fopen() or file_get_contents().
Example:
$options = [
'http' => [
'method' => 'GET'
'header' => 'User-Agent: PHP'
]
];
$context = stream_context_create($options);
$content = file_get_contents('http://example.com', false, $context);
echo $content; 61 What is error handling in PHP and what functions are used?
What is error handling in PHP and what functions are used?
Error Handling in PHP
Error handling in PHP involves detecting and responding to runtime errors to prevent script crashes or unexpected behavior. PHP provides built-in mechanisms like error reporting levels and custom error handlers.
Common functions:
error_reporting()— Sets which types of errors are reported.set_error_handler()— Defines a custom function to handle errors.trigger_error()— Manually triggers an error.- Using
try-catchblocks with exceptions to handle runtime errors gracefully.
62 What is the difference between errors and exceptions in PHP?
What is the difference between errors and exceptions in PHP?
Errors vs Exceptions in PHP
Errors are issues that occur during script execution, such as syntax errors, undefined variables, or runtime failures. They often halt script execution if not handled.
Exceptions, on the other hand, are objects representing abnormal conditions that can be thrown and caught using try-catch blocks. They allow developers to manage error conditions in a structured, object-oriented way without terminating the script abruptly.
Example:
try {
if(!file_exists('file.txt')) {
throw new Exception('File not found');
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} 63 How do you handle exceptions in PHP?
How do you handle exceptions in PHP?
Handling Exceptions in PHP
Exceptions allow you to manage runtime errors without stopping script execution abruptly. The try block contains code that may throw an exception. If an exception occurs, it is passed to a catch block for proper handling. This enables the developer to log errors, show custom messages, or take corrective actions.
The optional finally block executes cleanup code regardless of whether an exception was thrown or not. This is useful for closing files, releasing resources, or database connections.
Example:
try {
$file = fopen('data.txt', 'r');
if (!$file) {
throw new Exception('File not found');
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} finally {
echo 'Script finished execution';
} 64 What is the difference between include, require, include_once, and require_once?
What is the difference between include, require, include_once, and require_once?
Include vs Require in PHP
include and require both load external files, but behave differently when the file is missing. include raises a warning and the script continues, while require triggers a fatal error stopping execution.
The _once variants prevent multiple inclusions of the same file, which is helpful to avoid redeclaration of functions or classes. Use require_once for essential files and include_once for optional files.
Example:
include 'optional.php';
require_once 'config.php'; 65 What is an associative array in PHP?
What is an associative array in PHP?
Associative Arrays
Associative arrays in PHP allow developers to store key-value pairs where keys are strings. This is useful for structured data like user profiles, settings, or mapping values.
Unlike indexed arrays that use numeric indexes, associative arrays improve code readability and simplify data access by using meaningful keys.
Example:
$user = [
'name' => 'John'
'email' => 'john@example.com'
'age' => 30
];
echo $user['email']; // Outputs john@example.com 66 What are PHP array functions commonly used?
What are PHP array functions commonly used?
Common PHP Array Functions
PHP arrays can be manipulated using a wide variety of built-in functions. These functions help in adding, removing, merging, or searching array elements efficiently.
Examples of commonly used functions include:
array_merge(): Combines arrays into one.array_push(): Adds elements to the end of an array.array_pop(): Removes the last element.array_keys()andarray_values(): Retrieve keys or values.in_array(): Checks if a value exists.
67 What is the difference between indexed, associative, and multidimensional arrays in PHP?
What is the difference between indexed, associative, and multidimensional arrays in PHP?
Types of Arrays
PHP supports three main types of arrays:
- Indexed arrays: Numeric keys starting from 0.
- Associative arrays: String keys for easier access.
- Multidimensional arrays: Arrays containing arrays, used for representing tables or matrices.
Example:
$indexed = [1,2,3];
$assoc = ['name'=>'Alice','age'=>25];
$multi = [
['a', 'b']
['c', 'd']
]; 68 What is type hinting in PHP?
What is type hinting in PHP?
Type Hinting in PHP
Type hinting specifies the expected data types of function parameters or return values. PHP will throw a TypeError if the wrong type is passed. This makes code more predictable, reduces bugs, and improves readability.
Supported types include scalar types (int, float, string, bool), arrays, callable, and objects.
Example:
function add(int $a, int $b): int {
return $a + $b;
}
add(5, 10); // Works
add('5', 10); // TypeError 69 What is return type declaration in PHP?
What is return type declaration in PHP?
Return Type Declarations
Return type declarations specify the expected type of a function's return value. If the function returns a value of a different type, PHP throws a TypeError.
This feature improves code clarity, ensures consistency, and helps detect bugs early.
Example:
function getName(): string {
return 'Alice';
}
$name = getName(); // Always a string 70 What are anonymous functions and closures in PHP?
What are anonymous functions and closures in PHP?
Anonymous Functions and Closures
Anonymous functions in PHP are functions without a name. They are often assigned to variables or passed as arguments to other functions, providing flexibility and modularity.
Closures are special anonymous functions that can access variables from the parent scope using the use keyword. This allows the function to maintain state and work with external variables.
Example:
$greet = function($name) {
return 'Hello ' . $name;
};
echo $greet('John'); // Hello John
$message = 'Welcome';
$closure = function($name) use ($message) {
return $message . ', ' . $name;
};
echo $closure('Alice'); // Welcome, Alice 71 What is a generator in PHP?
What is a generator in PHP?
Generators in PHP
Generators provide an efficient way to iterate over large datasets without loading everything into memory at once. Instead of returning an entire array, they yield values one by one, maintaining state between iterations.
This is especially useful for reading large files, processing streams, or any scenario where memory usage is critical.
Example:
function numbers() {
for ($i = 1; $i <= 5; $i++) {
yield $i;
}
}
foreach (numbers() as $num) {
echo $num . ' ';
} 72 What is the difference between traits and interfaces in PHP?
What is the difference between traits and interfaces in PHP?
Traits vs Interfaces in PHP
Traits are used for code reuse. They allow you to define methods that multiple classes can include, reducing duplication. Traits can contain method implementations, properties, and static methods.
Interfaces, on the other hand, only define method signatures. They enforce a contract, requiring implementing classes to define all methods declared in the interface. Interfaces cannot contain method bodies.
Example:
trait Logger {
public function log($msg) {
echo $msg;
}
}
interface Worker {
public function work();
}
class Developer implements Worker {
use Logger;
public function work() {
echo 'Writing code';
}
} 73 What is the difference between final class and final method in PHP?
What is the difference between final class and final method in PHP?
Final Classes and Final Methods
A final class is a class that cannot be inherited. It is used to prevent modification through subclassing, ensuring its implementation remains intact.
A final method is a method in a class that cannot be overridden in subclasses. This is useful when you want a specific method's behavior to remain unchanged while allowing the class to be extended.
Example:
final class BaseClass {
public function show() {
echo 'Final class cannot be extended';
}
}
class Child extends BaseClass { // Error
} 74 What are PHP namespaces?
What are PHP namespaces?
Namespaces in PHP
Namespaces are a way to encapsulate and organize code, allowing multiple classes, functions, or constants to coexist without naming conflicts. They are declared using the namespace keyword at the top of the PHP file.
Namespaces are especially useful in large projects or when integrating third-party libraries, avoiding collisions between class or function names.
Example:
namespace MyAppControllers;
class UserController {
public function index() {
echo 'User Index';
}
} 75 What is the SPL in PHP?
What is the SPL in PHP?
Standard PHP Library (SPL)
SPL provides a collection of ready-to-use interfaces, classes, and functions that facilitate common tasks like iterators, data structures (stack, queue, linked list), file handling, and exceptions.
It reduces the need to implement these features from scratch and ensures consistency in code.
Example:
$stack = new SplStack();
$stack->push(1);
$stack->push(2);
echo $stack->pop(); // 2 76 What is output buffering in PHP?
What is output buffering in PHP?
Output Buffering
Output buffering allows PHP to capture output in a buffer rather than sending it immediately to the browser. This is useful for controlling when and how content is sent, modifying output, or preventing header errors.
Functions like ob_start() start buffering, ob_get_clean() retrieves and clears the buffer, and ob_end_flush() sends buffered content to the browser.
Example:
ob_start();
echo 'Hello World';
$content = ob_get_clean();
echo strtoupper($content); // Outputs HELLO WORLD 77 What are PHP headers and how do you use them?
What are PHP headers and how do you use them?
PHP Headers
Headers are HTTP instructions sent to the client before any output. They control response codes, content type, redirects, caching, and more.
They must be called before any HTML or echo statements to avoid 'headers already sent' errors.
Example:
header('Content-Type: application/json');
header('Location: /home.php'); 78 What is the difference between GET and POST in terms of security?
What is the difference between GET and POST in terms of security?
GET vs POST Security
GET appends parameters to the URL, making them visible to users, logs, and browser history. Sensitive information like passwords should never be sent via GET.
POST sends data in the request body, hidden from the URL. It is more suitable for sensitive data and large payloads. Both methods should still be validated and sanitized to prevent attacks.
Example:
// GET: /login.php?user=John&pass=123
// POST: Sent in body, not visible in URL 79 What are cookies in PHP and how do you set them?
What are cookies in PHP and how do you set them?
Cookies in PHP
Cookies are key-value pairs stored on the client’s browser to remember information across requests, like user preferences or login sessions.
They are set using setcookie() before any output and can include parameters for expiry, path, domain, secure, and HttpOnly flags.
Example:
setcookie('username', 'John', time() + 3600, '/');
echo $_COOKIE['username']; 80 What is the difference between session_unset() and session_destroy()?
What is the difference between session_unset() and session_destroy()?
session_unset() vs session_destroy()
session_unset() clears all session variables in memory, but the session itself remains active, and the session cookie is unchanged.
session_destroy() destroys the session entirely, removing session data from the server and invalidating the session ID. After destroying, a new session must be started to continue storing data.
Example:
session_start();
$_SESSION['user'] = 'John';
session_unset(); // Clears variables
session_destroy(); // Ends session completely 81 What is a PHP daemon script?
What is a PHP daemon script?
A PHP daemon script is a PHP program designed to run continuously in the background instead of executing once per HTTP request. Daemons are often used for long-running tasks that don’t require direct browser interaction.
Use Cases
- Message queue consumers (RabbitMQ, Kafka).
- Monitoring servers/services.
- Long-running scheduled tasks (similar to cron jobs).
Basic Example
<?php
while (true) {
file_put_contents('log.txt', "Daemon active at: " . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
sleep(5); // wait 5 seconds before next iteration
}
In Linux, daemons are usually started from the command line or via systemdsupervisord, etc.
Key Notes
- Run daemon scripts from CLI, not web server.
- Must handle logging and memory management to avoid leaks.
82 What is opcache in PHP?
What is opcache in PHP?
Opcache is a built-in PHP extension that improves performance by storing precompiled script bytecode in memory. This avoids recompiling PHP scripts on each request.
How It Works
- Without Opcache – PHP parses scripts, compiles to bytecode, and executes on every request.
- With Opcache – PHP bytecode is cached in memory, reused for subsequent requests, speeding up execution.
Enabling Opcache (php.ini)
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
Benefits
- Faster performance (reduces CPU overhead of parsing/compiling).
- Lower server load.
- Essential for high-traffic applications.
83 What are PSR-4 autoloading standards?
What are PSR-4 autoloading standards?
PSR-4 is a PHP Standards Recommendation that defines how to autoload classes using file paths mapped to namespaces. It is widely used with Composer.
Main Concept
- The namespace of a class corresponds directly to its folder structure.
- Autoloaders automatically require the right file without manual include/require.
Example Project Structure
src/
└── App/
└── Controllers/
└── HomeController.php
Class
<?php
namespace App\Controllers;
class HomeController {
public function index() { echo "Hello"; }
}
Composer.json Autoload Section
{
"autoload": {
"psr-4": {
"App\\": "src/App/"
}
}
}Running composer dump-autoload generates an autoloader so classes are auto-included when used.
84 What is the difference between echo, print, and printf in PHP?
What is the difference between echo, print, and printf in PHP?
PHP provides several ways to output strings: echoprint, and printf. They serve different purposes:
echo
- Outputs one or more strings.
- Does not return a value.
echo "Hello ", "World"; // Hello World- Outputs a single string.
- Returns 1 (so it can be used in expressions).
if (print("Hello")) {
echo " Printed!";
}printf
- Outputs a formatted string based on format specifiers.
$name = "Alice";
printf("Hello, %s!", $name); // Hello, Alice!Summary
| Function | Can output multiple strings? | Return Value | Formatting? |
|---|---|---|---|
| echo | Yes | No | No |
| No | 1 | No | |
| printf | No | Integer (length of output) | Yes |
85 What is the use of die() and exit() in PHP?
What is the use of die() and exit() in PHP?
die() and exit() in PHP are identical functions used to terminate script execution immediately.
Basic Usage
if (!file_exists("data.txt")) {
die("File not found. Exiting...");
}
// or using exit
exit("Something went wrong");Key Notes
- If passed a string, it will be printed before termination.
- If passed an integer, it becomes the exit status code.
die()is simply an alias ofexit()(completely interchangeable).
Example with Status Code
exit(1); // exit program with status code 1 (common for errors) 86 What is the difference between isset() and empty() in PHP?
What is the difference between isset() and empty() in PHP?
isset() and empty() are often confused in PHP, but they serve different purposes in checking variables.
isset()
- Returns true if the variable is defined and not
null. - Returns false if variable is not set or explicitly
null.
$x = 0;
var_dump(isset($x)); // true
$y = null;
var_dump(isset($y)); // falseempty()
- Returns true if variable is considered empty.
- Empty values: 0, '', "0", null, false, array().
$x = 0;
var_dump(empty($x)); // true
$name = '';
var_dump(empty($name)); // trueComparison Table
| Function | Checks | Example true for |
|---|---|---|
| isset() | Defined & not null | $x=0, $x='' (true) |
| empty() | Falsy/empty values | 0, '', '0', false, [] |
Tip: Use isset() when checking if a variable exists, and empty() when checking if it has useful content.
87 What is the difference between == and != operators?
What is the difference between == and != operators?
In PHP, == and != are comparison operators that perform equality checks with type juggling (automatic type conversion).
== (Equality Operator)
- Compares two values for equality after type conversion if needed.
- Returns
trueif values are equal.
var_dump(5 == '5'); // true (string converted to int)!= (Inequality Operator)
- Checks if two values are not equal (after type conversion).
var_dump(5 != '10'); // trueImportant Note
For more predictable results without type juggling, use === (strict equal) and !== (strict not equal).
88 What are references in PHP?
What are references in PHP?
A reference in PHP means that two variables refer to the same memory location. Changing one variable updates the other, because they are essentially aliases.
Creating a Reference
$a = 10;
$b =& $a; // $b references $a
$b = 20;
echo $a; // 20 (also updated)Use Cases
- Function parameters: pass by reference so the function can modify the original variable.
function increment(&$num) { $num++; }
$x = 5;
increment($x);
echo $x; // 6 89 What is the use of the clone keyword in PHP?
What is the use of the clone keyword in PHP?
The clone keyword in PHP creates a shallow copy of an object. By default, the new object has copies of the original properties, but nested objects are still referenced.
Basic Example
class Person {
public $name;
}
$p1 = new Person();
$p1->name = 'Alice';
$p2 = clone $p1;
$p2->name = 'Bob';
// Different objects now
var_dump($p1->name, $p2->name);__clone() Magic Method
Define custom cloning behavior:
class User {
public $id;
public function __clone() {
$this->id = null; // reset id on clone
}
} 90 What is the difference between shallow copy and deep copy in PHP?
What is the difference between shallow copy and deep copy in PHP?
When copying objects, the difference is in how nested (referenced) objects are treated:
Shallow Copy (clone)
- Copies only the top-level properties.
- If a property contains an object, the reference is copied, not the object itself.
Deep Copy
- Recursively copies all objects, creating independent data copies.
Example
class Address { public $city; }
class Person { public $name; public $address; }
$a = new Address();
$a->city = 'Paris';
$p1 = new Person();
$p1->name = 'Alice';
$p1->address = $a;
$p2 = clone $p1; // shallow copy
$p2->address->city = 'London';
// Both show 'London' due to shared referenceTo create deep copies, you must implement a custom __clone() method that also clones nested objects.
91 What are PHP superglobals?
What are PHP superglobals?
Superglobals are predefined global arrays in PHP that are always available in any scope without needing global declaration. They are used to manage input data, sessions, environment variables, etc.
Main Superglobals
$_GET– Data from URL query parameters$_POST– Data from HTML forms (POST method)$_REQUEST– Combination of GET, POST, COOKIE$_SESSION– Session variables$_COOKIE– Cookies set in browser$_SERVER– Server/environment details$_FILES– Uploaded files info$_ENV– Environment variables
92 What is the use of $_SERVER in PHP?
What is the use of $_SERVER in PHP?
$_SERVER is a superglobal in PHP that contains information about headers, paths, script locations, and the current HTTP request/response environment.
Examples
echo $_SERVER['SERVER_NAME']; // localhost
// Request method
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo 'Form submitted via POST';
}
// Client IP address
echo $_SERVER['REMOTE_ADDR'];Common $_SERVER Keys
SERVER_NAME– The server’s host name.HTTP_USER_AGENT– Information about the browser/client.SCRIPT_FILENAME– Full path of the executing script.REQUEST_METHOD– GET, POST, etc.
93 What is the difference between $_REQUEST and $_POST in PHP?
What is the difference between $_REQUEST and $_POST in PHP?
Both are superglobals, but they hold different request data in PHP.
$_POST
- Contains form data sent via HTTP POST method only.
// Form example
<form method="POST" action="submit.php">
<input name="username">
</form>
// submit.php
echo $_POST['username'];$_REQUEST
- Contains a combination of data from
$_GET$_POST, and$_COOKIE. - Which order is applied depends on
php.ini(variables_order directive).
echo $_REQUEST['username']; // could come from GET, POST, or COOKIEBest Practice: Prefer $_POST or $_GET explicitly for clarity and security. Use $_REQUEST only when you truly want to mix sources.
94 What is PDO in PHP?
What is PDO in PHP?
PDO (PHP Data Objects) is a database access abstraction layer that provides a consistent API for working with multiple database systems (MySQL, PostgreSQL, SQLite, etc.).
Features
- One API for many databases.
- Support for prepared statements (security against SQL injection).
- Flexible error handling modes.
Example: Connecting with PDO
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query('SELECT * FROM users');
foreach ($stmt as $row) {
echo $row['username'];
}Best practice: Always use prepared statements with PDO instead of concatenating SQL strings.
95 What are prepared statements in PHP?
What are prepared statements in PHP?
Prepared statements are a way to execute SQL queries more securely and efficiently. The SQL statement is precompiled with placeholders, and values are bound separately to prevent injection attacks.
Advantages
- Security: Prevents SQL injection by separating SQL from user input.
- Performance: Query is parsed and compiled once, reused multiple times with different parameters.
PDO Example
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => 'alice@example.com']);
foreach ($stmt as $row) {
echo $row['username'];
}MySQLi Example
$mysqli = new mysqli('localhost','user','pass','test');
$stmt = $mysqli->prepare('SELECT * FROM users WHERE id = ?');
$stmt->bind_param('i', $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result(); 96 What is SQL injection and how do you prevent it in PHP?
What is SQL injection and how do you prevent it in PHP?
SQL Injection is a code injection attack where malicious users insert SQL statements into input fields to manipulate or extract database data.
Vulnerable Example
// DON'T DO THIS
$username = $_GET['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
If username=admin' OR '1'='1, query returns all users.
Prevention
- Use prepared statements with parameterized queries (PDO or MySQLi).
- Properly validate and sanitize input.
Safe Example (PDO)
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $_GET['username']]);
Best practice: Always use prepared statements. Avoid concatenating user input directly into queries.
97 What is cross-site scripting (XSS) and how do you prevent it in PHP?
What is cross-site scripting (XSS) and how do you prevent it in PHP?
Cross-site scripting (XSS) is an attack where attackers inject JavaScript or HTML into web pages, which executes in the victim’s browser.
Example of Vulnerability
// Bad: user input is displayed directly
echo $_GET['name'];If attacker sends: <script>alert('Hacked!')</script>, script runs in browser.
Prevention
- Escape all output:
htmlspecialchars(). - Validate and sanitize input.
- Use Content Security Policy (CSP).
Safe Example
// Safe output
echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
Best practice: Always sanitize output, not just input, since XSS happens when untrusted data is rendered in HTML.
98 What is CSRF and how can you prevent it in PHP?
What is CSRF and how can you prevent it in PHP?
CSRF (Cross-Site Request Forgery) is an attack where a user is tricked into performing an unwanted action on a web app where they are authenticated.
Example
// User is logged in. Attacker sends hidden request:
<img src="http://yourbank.com/transfer?amount=1000&to=hacker" />If no checks exist, the transfer is executed under user’s session.
Prevention Methods
- Use CSRF tokens: Unique per form/request.
- Same-site cookies for session identifiers.
- Check
RefererorOriginheaders (extra layer).
Example CSRF Token
// Generate token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// In form
<input type="hidden" name="csrf_token" value="{$_SESSION['csrf_token']}">
// On form submit
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('Invalid CSRF token');
} 99 What is password hashing in PHP and which functions are recommended?
What is password hashing in PHP and which functions are recommended?
Password hashing means converting plain-text passwords into irreversible hashes to protect user credentials from attacks.
Best Practices
- Do not store plain-text passwords.
- Use
password_hash()in PHP for secure hashing (bcrypt/argon2). - Use
password_verify()during login.
Example
// Register
$hash = password_hash('mypassword', PASSWORD_BCRYPT);
// Login Check
if (password_verify('mypassword', $hash)) {
echo 'Password correct!';
}Recommended functions: password_hash()password_verify(), and password_needs_rehash() for updating hashes.
100 What is the difference between md5(), sha1(), and password_hash()?
What is the difference between md5(), sha1(), and password_hash()?
PHP provides different hashing methods, but not all are secure for passwords.
md5()
- Produces 32-character hash.
- Very fast, but insecure (rainbow tables, collisions).
echo md5('password'); // insecuresha1()
- Produces 40-character hash.
- Also fast but insecure against modern attacks.
echo sha1('password');password_hash()
- Uses adaptive algorithms (bcrypt, Argon2).
- Applies automatic salting.
- Slow by design (resistant to brute-force).
$hash = password_hash('password', PASSWORD_BCRYPT);
Comparison
| Function | Secure? | Use case |
|---|---|---|
| md5() | No | Legacy checksums |
| sha1() | No | Legacy data integrity |
| password_hash() | Yes | Password storage |
101 What are design patterns in PHP?
What are design patterns in PHP?
Design patterns are reusable, proven solutions to recurring software design problems. They provide templates for structuring code more efficiently.
Categories
- Creational – object creation (Singleton, Factory, Builder).
- Structural – object composition (Adapter, Decorator).
- Behavioral – communication/interaction (Observer, Strategy).
Example
// Singleton (Creational Pattern)
class Logger {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new Logger();
}
return self::$instance;
}
}Patterns make PHP applications more scalable, reusable, and easy to maintain.
102 Explain the Singleton pattern in PHP.
Explain the Singleton pattern in PHP.
The Singleton pattern ensures that only one instance of a class exists throughout the application lifecycle.
Implementation
- Private constructor to prevent creating objects using
new. - Static property to hold the single instance.
- Public static method
getInstance()returns the instance.
class DBConnection {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new DBConnection();
}
return self::$instance;
}
}
$db = DBConnection::getInstance();Use Cases
- Database connections.
- Logging systems.
- Caching managers.
103 Explain the Factory pattern in PHP.
Explain the Factory pattern in PHP.
The Factory pattern is a creational pattern used to create objects without exposing the creation logic to the client. Instead, a method (factory) decides which class to instantiate based on input or configuration.
Implementation
interface Shape { public function draw(); }
class Circle implements Shape {
public function draw() { echo "Drawing a Circle"; }
}
class Square implements Shape {
public function draw() { echo "Drawing a Square"; }
}
class ShapeFactory {
public static function create($type) {
if ($type == 'circle') return new Circle();
if ($type == 'square') return new Square();
throw new Exception("Unknown type");
}
}
$shape = ShapeFactory::create('circle');
$shape->draw();Use Cases
- Dynamic object creation based on conditions.
- Simplifies object creation logic for clients.
- Common in frameworks for dependency injection containers.
104 What is dependency injection in PHP?
What is dependency injection in PHP?
Dependency Injection (DI) is an OOP design pattern in which an object’s dependencies are injected from outside rather than being created inside the class. This makes code more flexible and testable.
Without Dependency Injection
class UserService {
private $db;
public function __construct() {
$this->db = new Database(); // tightly coupled
}
}With Dependency Injection
class UserService {
private $db;
public function __construct(Database $db) {
$this->db = $db; // injected dependency
}
}
$db = new Database();
$userService = new UserService($db);
Benefits
- Loose coupling – easier to switch implementations.
- Testability – can inject mock objects for unit tests.
- Flexibility – integrates well with frameworks (Laravel, Symfony) that have DI containers.
105 What is the difference between Composer require and require-dev?
What is the difference between Composer require and require-dev?
In Composer, dependencies can be categorized as require or require-dev, helping to separate production dependencies from development tools.
require
- Lists packages needed for your application to run in production.
- Examples: frameworks, database libraries, payment gateways.
composer require monolog/monologrequire-dev
- Lists packages used only during development/testing.
- Examples: PHPUnit, PHPStan, debugging tools.
composer require --dev phpunit/phpunitBest Practice
Use require for production dependencies and require-dev for testing or development utilities to keep production environments clean.
106 What is semantic versioning in PHP packages?
What is semantic versioning in PHP packages?
Semantic Versioning (SemVer) is a versioning scheme used in PHP (and most modern languages) to indicate compatibility and update types.
Format
MAJOR.MINOR.PATCHRules
- MAJOR – Breaking changes. Requires careful upgrades (e.g., 1.x → 2.0).
- MINOR – New features added, but backward compatible (e.g., 1.2 → 1.3).
- PATCH – Bug fixes, security fixes without new features (e.g., 1.2.1 → 1.2.2).
Example
"monolog/monolog": "^2.4"This means Composer can install any version >=2.4.0 and <3.0.0, ensuring no breaking changes.
107 What is the use of composer.lock file?
What is the use of composer.lock file?
The composer.lock file ensures reproducible builds by locking dependency versions.
How it Works
composer.jsondefines version constraints (e.g., ^1.2, ~2.0).composer.lockrecords the exact installed versions.- When another developer runs
composer install, the same versions are installed.
Example
// composer.json
"monolog/monolog": "^2.0"// composer.lock
"monolog/monolog": {
"version": "2.3.5",
"source": "..."
}Best Practice
Include composer.lock in version control to maintain consistency across environments (CI/CD, production, local dev).
108 What are autoloaders in PHP?
What are autoloaders in PHP?
Autoloaders automatically include class files in PHP when a class is referenced, avoiding manual require statements.
Example Without Autoloading
require 'src/Controllers/HomeController.php';
$controller = new HomeController();With Autoloading (Composer)
// composer.json
"autoload": {
"psr-4": {"App\\": "src/"}
}
// usage in code
use App\Controllers\HomeController;
$controller = new HomeController();
Composer generates vendor/autoload.php which loads classes based on PSR-4 namespace rules.
Benefits
- Cleaner code without manual includes.
- Supports PSR-4 standard.
- Essential for modern PHP frameworks (Laravel, Symfony).
109 What are the advantages of using frameworks in PHP?
What are the advantages of using frameworks in PHP?
PHP frameworks provide pre-built structure and common components to speed up application development and enforce best practices.
Advantages
- Code organization – MVC patterns ensure separation of concerns.
- Security features – CSRF protection, XSS filtering, SQL injection prevention.
- Faster development – built-in libraries (auth, sessions, routing).
- Reusability – reusable packages and components.
- Community support – frameworks have large ecosystems (e.g., Laravel’s community packages).
Example
Writing authentication from scratch is time-consuming. Laravel/Symfony provide secure, ready-made authentication components.
110 What are some popular PHP frameworks?
What are some popular PHP frameworks?
There are several widely used PHP frameworks, each with unique strengths:
Popular Frameworks
- Laravel – Most popular; expressive syntax, Eloquent ORM, Blade templating.
- Symfony – Enterprise-grade; highly flexible and modular.
- CodeIgniter – Lightweight, fast, suitable for small apps.
- Yii – High performance, strong for APIs.
- Zend Framework / Laminas – Enterprise-level, now continued as Laminas project.
- Phalcon – Extremely fast (written in C as a PHP extension).
Choosing a Framework
Laravel is often preferred for startups and rapid development, while Symfony suits complex enterprise projects.
111 What is MVC architecture in PHP frameworks?
What is MVC architecture in PHP frameworks?
MVC (Model-View-Controller) is a software architecture pattern commonly used in PHP frameworks like Laravel and Symfony.
Components
- Model – Represents the data and business logic (e.g., interacting with the database).
- View – Handles output/representation (e.g., HTML templates, Blade files).
- Controller – Handles user input, application flow, and connects Model to View.
Request Flow Example
- User makes request to
/users. - The Controller calls the Model to fetch user data.
- Data is passed to the View for rendering HTML output.
// Laravel example
class UserController extends Controller {
public function index() {
$users = User::all();
return view('users.index', compact('users'));
}
}
This separation improves maintainability, scalability, and teamwork (designers work on views, developers on controllers/models).
112 What is the difference between Laravel and CodeIgniter?
What is the difference between Laravel and CodeIgniter?
Both Laravel and CodeIgniter are popular PHP frameworks but they differ significantly in philosophy, features, and use cases.
Laravel
- Modern, feature-rich framework.
- Emphasizes elegant syntax and development speed.
- Comes with Eloquent ORM, Blade templating engine, Artisan CLI, built-in authentication and queue system.
- Large and active community, regular updates.
CodeIgniter
- Lightweight framework with fewer built-in features.
- Faster to get started, less opinionated, greater developer freedom.
- No built-in ORM (uses simple query builder instead).
- Great for small/medium projects where simplicity is preferred.
Comparison Table
| Feature | Laravel | CodeIgniter |
|---|---|---|
| ORM | Eloquent ORM | Basic Query Builder |
| Templating | Blade Engine | No built-in engine |
| CLI Tools | Artisan CLI | Minimal CLI support |
| Learning curve | Higher (rich ecosystem) | Lower (simpler) |
Summary: Choose Laravel for large, complex apps needing modern features. Choose CodeIgniter for smaller, fast applications with fewer dependencies.
113 What is Artisan in Laravel?
What is Artisan in Laravel?
Artisan is Laravel’s built-in command-line interface (CLI) tool. It automates common developer tasks like database migrations, code generation, and running jobs.
Common Artisan Commands
php artisan serve– start local development server.php artisan make:controller UserController– generate boilerplate controller code.php artisan migrate– run migrations.php artisan db:seed– seed test data.php artisan test– run PHPUnit tests.
Example
php artisan make:model Product -mcr
// Creates Model, Migration, Controller, Resource for ProductBenefit: Artisan boosts productivity by eliminating repetitive code tasks.
114 What are Laravel migrations?
What are Laravel migrations?
Migrations in Laravel act as version control for your database. They provide a structured way to define schema changes and share them across the team safely.
Benefits
- Database schema is written in PHP code instead of manual SQL.
- Version-controlled (teams apply same migrations consistently).
- Rollback support for reverting changes.
Example: Create Migration
php artisan make:migration create_users_tableMigration File
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});Running Migration
php artisan migrateConclusion: Migrations make database schema changes structured, reversible, and team-friendly.
115 What are Eloquent relationships in Laravel?
What are Eloquent relationships in Laravel?
Eloquent is Laravel’s ORM (Object-Relational Mapper). It allows defining relationships between models, simplifying complex queries with intuitive methods.
Types of Relationships
- One-to-One: Example: A user has one profile.
- One-to-Many: Example: A post has many comments.
- Many-to-Many: Example: A student belongs to many courses.
- Polymorphic: Example: Comments can belong to posts or videos.
Example: One-to-Many
// Post model
public function comments() {
return $this->hasMany(Comment::class);
}
// Usage
$post = Post::find(1);
foreach ($post->comments as $comment) {
echo $comment->content;
}Benefit: Relationships reduce raw SQL queries and make code more readable and expressive.
116 What is middleware in Laravel?
What is middleware in Laravel?
Middleware in Laravel acts as a filter for incoming requests. It processes requests before they reach controllers (and responses before they leave back to the client).
Common Uses
- Authentication (check if user is logged in).
- CSRF token verification for forms.
- Logging request and response data.
- Modifying headers (e.g., add CORS).
Example
// Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class
];
// Apply to route
Route::get('/dashboard', function () {
// only authorized users...
})->middleware('auth');Benefit: Middleware centralizes request filtering logic instead of repeating checks in each controller.
117 What are service providers in Laravel?
What are service providers in Laravel?
Service providers are the central place where all Laravel application services are registered. They tell Laravel what to load into the service container.
Features
- Register bindings in the service container.
- Load routes, event listeners, or middleware.
- Bootstrapping services for the application lifecycle.
Example
class AppServiceProvider extends ServiceProvider {
public function register() {
$this->app->bind('App\Contracts\Mailer', 'App\Services\SMTPMailer');
}
public function boot() {
// perform initialization tasks
}
}Benefit: Service providers give developers full control of application configuration and dependency injection, making Laravel highly extensible.
118 What is Blade templating engine in Laravel?
What is Blade templating engine in Laravel?
Blade is Laravel’s lightweight yet powerful templating engine. Unlike raw PHP templates, Blade provides expressive syntax, template inheritance, and reusable components that simplify building dynamic user interfaces.
Theory and Purpose
- Provides a clean separation of logic and presentation, following MVC principles.
- Supports template inheritance (layouts, sections, partials).
- Includes directives like
@if, @for, @foreach, @extendsto replace verbose PHP control structures. - Automatically escapes HTML output to prevent XSS attacks unless explicitly told otherwise.
Example – Layouts and Inheritance
<!-- layout.blade.php -->
@include('partials.header')
@yield('content')
<!-- home.blade.php -->
@extends('layout')
@section('content')
Hello, {{ $name }}
@endsectionBlade Directives
@if($user->isAdmin())
Welcome Admin
@endif
@foreach($users as $user)
{{ $user->name }}
@endforeachBlade Components
<!-- resources/views/components/alert.blade.php -->
{{ $message }}
<!-- usage -->
Best Practice: Use Blade components for UI reusability, layouts for consistency, and be mindful of escaping with {{ }} vs {!! !!}.
119 What is caching in Laravel?
What is caching in Laravel?
Caching is a technique where frequently-used data is stored temporarily to reduce the need for repeated processing or queries. In Laravel, caching improves performance by reducing database queries and API calls.
Laravel Cache System
- Abstraction layer: write once, and change drivers (file, Redis, Memcached, DB) without rewriting code.
- Supports key-value based storage.
- Configurable in
config/cache.php.
Cache Example
// Store value in cache for 10 minutes
Cache::put('user_1', $user, 600);
// Retrieve value
echo Cache::get('user_1');
// Delete from cache
Cache::forget('user_1');Remember Helper
$users = Cache::remember('users', 3600, function () {
return DB::table('users')->get();
});Cache Drivers
- File (default, not scalable).
- Database (shared in DB tables).
- Redis and Memcached (fast, best for production).
Best Practice: Use Redis or Memcached in production for distributed caching, and apply caching to queries, API responses, and expensive computations.
120 What are Laravel queues?
What are Laravel queues?
Queues in Laravel allow you to defer time-consuming tasks (like sending emails, resizing images, or processing jobs) to background workers instead of blocking the main request cycle.
Theory
- Queues improve user experience by moving heavy tasks outside the HTTP response cycle.
- Laravel provides a unified API for multiple queue backends (DB, Redis, SQS, Beanstalkd).
- Jobs can be re-queued on failure with retry policies.
Creating a Job
php artisan make:job ProcessOrder// handle() inside ProcessOrder
public function handle() {
Mail::to($this->user)->send(new OrderMail($this->order));
}Dispatching a Job
ProcessOrder::dispatch($order);Running Workers
php artisan queue:workBest Practice: Queues are vital for scalability. Always run queue workers with a process manager (Supervisor). Use Redis for high-volume jobs.
121 What is REST API and how is it implemented in PHP?
What is REST API and how is it implemented in PHP?
REST (Representational State Transfer) is an architectural style for building APIs that expose resources via HTTP methods. Each resource is identified by a URL and interacts statelessly.
Core HTTP Methods
GET– retrieve things (list or single resource).POST– create a new resource.PUT/PATCH– update an existing resource.DELETE– remove a resource.
Example in Laravel
Route::get('/api/users', [UserController::class, 'index']);
Route::post('/api/users', [UserController::class, 'store']);// inside UserController
public function index() {
return response()->json(User::all());
}Key REST Principles
- Statelessness – each request contains all needed info.
- Uniform interface – consistent use of URL and verbs.
- Representation – resources often returned in JSON.
Best Practice
Use standard HTTP response codes, secure APIs with authentication (JWT, OAuth2), and document endpoints with Swagger/OpenAPI.
122 What is GraphQL and how can it be used with PHP?
What is GraphQL and how can it be used with PHP?
GraphQL is a modern alternative to REST developed by Facebook. It allows clients to specify exactly what data they need, avoiding over-fetching or under-fetching from APIs.
GraphQL vs REST
- REST requires multiple endpoints (e.g., /users, /users/1/posts).
- GraphQL has a single endpoint where clients define queries.
- GraphQL returns only requested fields, REST returns fixed responses.
Example GraphQL Query
{
user(id: 1) {
name
email
posts {
title
}
}
}Using GraphQL with PHP
PHP libraries like webonyx/graphql-php or Laravel packages like Lighthouse provide GraphQL servers.
$queryType = new ObjectType([
'name' => 'Query'
'fields' => [
'user' => [
'type' => $userType
'args' => ['id' => Type::int()]
'resolve' => function($root, $args) {
return User::find($args['id']);
}
]
]
]);Best Practice: Use GraphQL when clients (like mobile apps, SPAs) need complex and flexible queries. Use caching and query limits to avoid overloading the server.
123 How does PHP handle WebSockets?
How does PHP handle WebSockets?
WebSockets provide two-way persistent communication between a server and client, unlike HTTP’s request-response model. They are essential for real-time features like chats, multiplayer games, and notifications.
How PHP Handles WebSockets
- Ratchet – A PHP library for building WebSocket servers.
- Swoole – A powerful async PHP extension supporting high-concurrency WebSocket applications.
- Laravel Echo + Pusher – Commonly used in Laravel for broadcasting events.
Ratchet Example
class Chat implements MessageComponentInterface {
public function onMessage($conn, $msg) {
foreach ($this->clients as $client) {
$client->send($msg);
}
}
}
// start server
$server = IoServer::factory(new HttpServer(new WsServer(new Chat())), 8080);
$server->run();WebSocket Use Cases
- Chat applications (WhatsApp-like).
- Stock/crypto tickers.
- Multiplayer online games.
- Real-time dashboards & notifications.
Best Practice: Use Swoole for high-performance production WebSockets. Use Laravel Echo for easy integration in Laravel apps with broadcasting support.
124 What is serverless architecture and can PHP be used in it?
What is serverless architecture and can PHP be used in it?
Serverless architecture is a cloud model where developers focus only on writing code. The infrastructure (scaling, patching, provisioning) is fully managed by the provider.
How It Works
- Your application runs as functions (Function-as-a-Service, FaaS).
- These functions execute in response to triggers (HTTP requests, events, file uploads).
- Billing is based on actual execution time, not server uptime.
PHP in Serverless
- AWS Lambda + Bref – Bref provides PHP runtimes for AWS Lambda.
- Google Cloud Functions – Can run PHP via custom runtime.
- OpenFaaS / Knative – Open source serverless platforms supporting PHP.
Example (AWS Lambda with Bref)
composer require bref/bref
# serverless.yml
functions:
hello:
handler: index.php
runtime: php-81-fpmBenefits
- No server management required.
- Scalability is automatic.
- Pay only for execution time.
Use Cases
- Event-driven applications.
- API endpoints.
- Image processing, short tasks.
Conclusion: PHP can be used in serverless environments with Bref (AWS Lambda) or custom runtimes, enabling cost-effective, scalable apps without dedicated servers.
125 What are command-line PHP scripts and their uses?
What are command-line PHP scripts and their uses?
A command-line PHP script (CLI script) is a PHP program executed directly in the terminal without requiring a web server like Apache or Nginx. These scripts run in standalone mode and are widely used for tasks beyond web request-response cycles.
Key Features
- Executed via
php script.phpin the terminal. - No HTTP request/response context (no $_GET, $_POST by default).
- Access to command-line arguments (
$argv).
Example
// script.php
if ($argc > 1) {
echo "Hello, {$argv[1]}";
} else {
echo "Hello, World";
}
// Run in terminal:
php script.php Alice
// Output: Hello, AliceUses
- Cron Jobs – Automated recurring tasks (backups, sending reports).
- Daemons – Background workers (queue processing, monitoring).
- One-time tasks – Data migration, batch processing, importing CSV/JSON files.
Best Practice: Always validate CLI arguments, log errors to a file, and run long-living scripts under supervisors or process managers.
126 How do you implement logging in PHP applications?
How do you implement logging in PHP applications?
Logging is a key practice to record application activity, errors, and debugging information for monitoring and troubleshooting PHP applications.
Native PHP Logging
error_log()– Built-in function to log messages to server logs or custom files.
error_log("User login failed for user ID 42", 3, "/var/log/php_errors.log");Logging with Monolog
- Monolog is the de-facto logging library in PHP and Laravel uses it internally.
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$log = new Logger('app');
$log->pushHandler(new StreamHandler(__DIR__.'/app.log', Logger::WARNING));
$log->warning('Low disk space');
$log->error('Application crashed');Framework Logging
- Laravel:
Log::info()Log::error()wrappers around Monolog. - Symfony: uses PSR-3 compatible loggers.
Best Practices
- Follow PSR-3 logging standard for consistency.
- Use multiple channels (file, syslog, cloud providers like AWS CloudWatch).
- Log with appropriate levels – info, warning, error, critical.
127 What is Composer and why is it used?
What is Composer and why is it used?
Composer is PHP’s official dependency manager. It allows developers to declare the libraries their project depends on and installs them automatically, ensuring consistent versions across environments.
Key Features
- Manages project dependencies via
composer.jsonfile. - Handles autoloading (PSR-4, PSR-0).
- Helps with semantic versioning and reproducibility.
Basic Example
// Install a library
composer require monolog/monolog
// Autoload
require 'vendor/autoload.php';
use Monolog\Logger;Uses
- Installing and managing third-party libraries.
- Loading classes automatically (no manual require).
- Creating reusable PHP packages for distribution.
Best Practice: Commit composer.lock to version control to ensure consistent dependencies across dev, staging, and production.
128 How can you secure file uploads in PHP?
How can you secure file uploads in PHP?
File uploads are a common feature but also a security risk if not handled properly. Hackers may upload malicious scripts disguised as images or files.
Security Steps
- Validate file type – allow only expected MIME types (e.g., jpg, png, pdf).
- Validate file size – prevent large files causing DoS attacks.
- Store outside web root – prevents direct execution of uploaded files via URL.
- Rename/unique filenames – avoid collisions and path guessing.
- Virus/malware scanning – integrate with ClamAV or similar scanners.
Sample Secure Upload
if ($_FILES['upload']['error'] === UPLOAD_ERR_OK) {
$fileTmpPath = $_FILES['upload']['tmp_name'];
$fileName = uniqid().".jpg";
$dest = '/var/www/uploads/'.$fileName;
move_uploaded_file($fileTmpPath, $dest);
}Best Practice: Never allow direct execution of uploaded files. Always validate & sanitize user inputs and MIME types.
129 How does PHP handle session hijacking and prevention?
How does PHP handle session hijacking and prevention?
Session hijacking occurs when an attacker steals or guesses a valid session ID to impersonate a user. Since PHP sessions are cookie-based by default, care must be taken to protect them.
Prevention Techniques
- Use secure cookies: Enable
session.cookie_secureandHttpOnly. - Regenerate session ID: After login, use
session_regenerate_id(true)to prevent fixation. - Use HTTPS (TLS): Prevents session ID sniffing in transit.
- Validate user info: Tie session to IP and User-Agent for extra validation.
Example
session_start();
if (!isset($_SESSION['user'])) {
header("Location: login.php");
}
// Regenerate ID after login
session_regenerate_id(true);Best Practice: Always store sensitive sessions over HTTPS only, and limit session lifetimes with inactivity timeouts.
130 What is the difference between HTTP and HTTPS in PHP applications?
What is the difference between HTTP and HTTPS in PHP applications?
HTTP and HTTPS are protocols for transmitting data between browsers and servers.
HTTP (Hypertext Transfer Protocol)
- Unencrypted – data travels in plain text.
- Vulnerable to sniffing, MITM attacks.
HTTPS (HTTP Secure)
- Uses SSL/TLS to encrypt communication.
- Secures login forms, payment data, cookies.
- Essential for GDPR, PCI-DSS compliance.
Implementation in PHP
// Force HTTPS in Laravel
if (!$request->secure()) {
return redirect()->secure($request->getRequestUri());
}Best Practice: Always use HTTPS (with HSTS headers) for production apps. Never allow session cookies over HTTP.
131 How do you perform unit testing in PHP?
How do you perform unit testing in PHP?
Unit testing is the practice of testing small, isolated pieces of code (like functions or classes) to ensure they behave as expected. In PHP, the most popular tool for unit testing is PHPUnit.
Setup PHPUnit
composer require --dev phpunit/phpunitExample Test
// src/Calculator.php
class Calculator {
public function add($a, $b) {
return $a + $b;
}
}
// tests/CalculatorTest.php
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase {
public function testAdd() {
$calc = new Calculator();
$this->assertEquals(4, $calc->add(2,2));
}
}Running Tests
./vendor/bin/phpunit testsBest Practices
- Follow TDD (Test-Driven Development) where appropriate.
- Write tests for both expected and edge cases.
- Run tests in CI/CD pipelines for automation.
Unit testing improves code reliability, prevents regressions, and enhances maintainability in PHP applications.
132 What is integration testing in PHP?
What is integration testing in PHP?
Integration testing is a testing approach that verifies whether different parts (modules/services) of an application work correctly together. Unlike unit tests, which test isolated pieces, integration tests check combined behavior.
Why Important?
- Ensures modules interact properly (e.g., authentication + database + API).
- Detects issues caused by configuration, environment differences, or external dependencies.
- Prepares the application for full end-to-end testing.
PHP Implementation (PHPUnit + Database)
// tests/Integration/DatabaseTest.php
use PHPUnit\Framework\TestCase;
class DatabaseTest extends TestCase {
public function testUserInsertAndRetrieve() {
$user = new User(['name' => 'Alice']);
$user->save();
$this->assertEquals('Alice', User::find($user->id)->name);
}
}
Examples of Integration Tests
- Testing database queries with Eloquent models.
- Verifying API responses via HTTP requests.
- Checking file uploads + storage working together.
Best Practice: Use a separate test database, seed mock data, and automate integration tests in CI/CD pipeline.
133 How can you measure code coverage in PHP?
How can you measure code coverage in PHP?
Code coverage measures the percentage of your codebase that executes while running tests. It indicates which parts of the code have been tested and which are untested.
Importance
- Helps ensure critical paths of the code are tested.
- Highlights dead/unreachable code.
- Drives better testing strategy (TDD/BDD).
Tools in PHP
- PHPUnit – built-in support with coverage reports using Xdebug or PCOV.
- Xdebug / PCOV – extensions required for coverage data.
Example Command
./vendor/bin/phpunit --coverage-html coverage/Output
Generates HTML reports showing what % of lines, functions, and branches are tested.
Best Practice: Aim for meaningful coverage (70–90%). 100% coverage does not guarantee bug-free code.
134 What are PHP assertions?
What are PHP assertions?
Assertions are expressions used to test assumptions made in code. If the assertion condition fails (evaluates to false), PHP can generate a warning/error, making debugging easier.
Basic Example
ini_set('assert.active', 1); // enable
assert(2 + 2 == 4); // passes
assert(1 > 2); // failsUse Cases
- Ensure function contracts (input/output expectations).
- Debugging during development.
- Catch logical errors early.
PHPUnit Assertions
Assertions are also used in PHPUnit testing to validate expected outcomes:
$this->assertEquals(5, $calc->add(2,3));Best Practice: Use assertions during development and testing, but don’t rely on them for runtime validation in production. For that, use proper exceptions and error handling.
135 How do you track and fix memory leaks in PHP?
How do you track and fix memory leaks in PHP?
A memory leak in PHP occurs when scripts consume memory but fail to release it, eventually exhausting resources. While PHP uses garbage collection, leaks can happen with long-running scripts (daemons, workers).
Causes of Memory Leaks
- Unreleased large arrays or objects.
- Circular references between objects.
- Open file handles or database connections not closed.
- Global variables proliferating unexpectedly.
Tracking Leaks
- Xdebug – profiling memory usage.
- PHP memory_get_usage() – check script memory consumption.
echo memory_get_usage();
// work...
echo memory_get_usage();Fixing Memory Leaks
unset()unused variables.- Close DB or file connections promptly.
- Break circular references between objects.
- Use queues/workers with process recycling (e.g., Supervisor for Laravel workers).
Best Practice: Always test CLI daemons/workers for memory leaks through profiling. Use tools like Blackfire for advanced memory profiling in production.
136 What are PHP filters and how are they used?
What are PHP filters and how are they used?
PHP Filters are built-in functions used for input validation and sanitization. They protect applications from invalid or malicious data (like faulty emails, unsafe URLs).
Common Functions
filter_var()– validates/sanitizes a variable.filter_input()– validates/sanitizes external input (GET, POST, COOKIE).
Examples
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
}$url = "https://example.com";
echo filter_var($url, FILTER_SANITIZE_URL);Available Filters
- FILTER_VALIDATE_EMAIL
- FILTER_VALIDATE_URL
- FILTER_VALIDATE_INT
- FILTER_SANITIZE_STRING
Best Practice: Always validate/sanitize input data on the server side, regardless of client-side validation. Input validation is the first defense against injection attacks.
137 What is content delivery network (CDN) and its relevance to PHP applications?
What is content delivery network (CDN) and its relevance to PHP applications?
A Content Delivery Network (CDN) is a geographically distributed network of servers that cache and deliver static assets like images, CSS, JS, and sometimes dynamic content. PHP apps rely on CDNs to offload static content delivery for faster global performance.
How It Works
- User requests static content (image, JS, CSS).
- Nearest CDN node serves cached content instead of origin server.
- If content not cached, CDN fetches from origin and caches it.
Relevance to PHP Applications
- Reduces server bandwidth (PHP server free for dynamic logic).
- Decreases latency by serving from closest edge location.
- Improves scalability for traffic spikes.
Example
Instead of serving images via http://mysite.com/images/logo.png, you can serve via https://cdn.mysite.com/logo.png.
Best Practice
Use CDNs like Cloudflare, Akamai, or AWS CloudFront. Always version (cache-bust) assets so CDN updates deliver fresh files when code changes.
138 What is lazy loading in PHP?
What is lazy loading in PHP?
Lazy loading is a design pattern where resource-intensive objects (or data) are created only when they are first required, not upfront. This improves performance and saves memory.
Example in Plain PHP
class Product {
private $details;
public function getDetails() {
if ($this->details === null) {
$this->details = $this->loadFromDatabase();
}
return $this->details;
}
}Here, product details are loaded from the database only when getDetails() is called.
Laravel Eloquent Lazy Loading
$posts = Post::all();
foreach ($posts as $post) {
echo $post->comments; // triggers separate query per post
}This is lazy-loading of related models – executed only when accessed.
Advantages
- Saves memory and initialization overhead.
- Improves performance when not all resources are needed immediately.
Disadvantage
- Can cause N+1 query problem if misused (e.g., too many DB queries).
Best Practice: Use lazy loading for expensive or optional resources, but prefer eager loading (with() in Laravel) when you know related data will be needed in bulk.
139 What is connection pooling and why is it useful?
What is connection pooling and why is it useful?
Connection pooling is the technique of keeping a pool of reusable database connections instead of creating a new one for every request. This approach drastically reduces overhead in high-traffic PHP applications.
Theory
- Opening and closing DB connections is expensive (authentication, TCP handshake).
- Pools maintain a set number of connections ready to use.
- When a request needs a connection, one is borrowed from the pool and returned after use.
Why Useful in PHP?
- Improves performance by avoiding repetitive connection setups.
- Reduces server load on database.
- Handles concurrency better under heavy traffic.
Implementation
Native PHP doesn’t keep connections alive across requests because PHP scripts usually end after execution. However, connection pooling is achieved via:
- Persistent connections – using
PDO::ATTR_PERSISTENT. - Proxy layers like PgBouncer (Postgres) or ProxySQL (MySQL).
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass', [
PDO::ATTR_PERSISTENT => true
]);Best Practice: For enterprise PHP apps, use external pooling systems (PgBouncer/ProxySQL) instead of relying on PHP alone.
140 How does PHP support NoSQL databases?
How does PHP support NoSQL databases?
NoSQL databases provide flexible schemas and high scalability compared to relational databases. PHP interacts with them via extensions or external libraries.
Popular NoSQL Databases in PHP
- MongoDB – Document-oriented database.
- Redis – In-memory key-value store.
- Cassandra – Wide-column database for large-scale operations.
MongoDB Example
require 'vendor/autoload.php';
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->test->users;
$collection->insertOne(['name' => 'Alice']);Redis Example
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('user:1', 'Alice');
echo $redis->get('user:1');Best Practice: Use NoSQL for high-volume, schema-less, or caching workloads, but combine with relational DBs when transactional integrity is vital.
141 What is the difference between GET, POST, PUT, DELETE methods in PHP?
What is the difference between GET, POST, PUT, DELETE methods in PHP?
These are common HTTP methods used in RESTful APIs and web requests.
GET
- Used to retrieve data.
- Data passed via URL (
$_GET). - Idempotent (safe to repeat).
// URL: /user.php?id=1
echo $_GET['id'];POST
- Used to send data for creation.
- Data in request body (
$_POST). - Not idempotent.
// Form data sent via POST
echo $_POST['username'];PUT
- Used to update existing resources.
- Accessed via
php://inputin PHP.
parse_str(file_get_contents("php://input"), $_PUT);
echo $_PUT['name'];DELETE
- Used to delete resources.
- Also read using
php://input.
parse_str(file_get_contents("php://input"), $_DELETE);
echo $_DELETE['id'];Summary: GET=Retrieve, POST=Create, PUT=Update, DELETE=Remove. PHP handles GET/POST natively, but PUT/DELETE need manual parsing.
142 What are RESTful routes in PHP frameworks?
What are RESTful routes in PHP frameworks?
RESTful routes follow REST conventions by mapping HTTP verbs and URIs to controller actions. PHP frameworks like Laravel and Symfony provide built-in support for defining RESTful resource routes.
Example in Laravel
Route::resource('users', UserController::class);This generates routes automatically:
- GET /users → index()
- GET /users/{id} → show()
- POST /users → store()
- PUT/PATCH /users/{id} → update()
- DELETE /users/{id} → destroy()
Example in Slim Framework
$app->get('/users', 'UserController:index');
$app->post('/users', 'UserController:store');Benefit: RESTful routes enforce consistency, simplify APIs, and align with HTTP standards.
143 How do you implement authentication in PHP applications?
How do you implement authentication in PHP applications?
Authentication ensures that only valid users can access certain parts of a PHP application. Different methods are available based on context.
Session-Based Authentication
- Most common method, storing session ID in a secure cookie.
- Used in traditional PHP apps with forms and server-rendered pages.
// login.php
if ($username == 'admin' && $password == 'secret') {
$_SESSION['user'] = $username;
}Token-Based Authentication (JWT)
- Stateless, no session required.
- Common in APIs with mobile or SPA clients.
$token = JWT::encode(['user_id' => 1], $secretKey);OAuth Authentication
Allows authentication via third-party providers like Google, Facebook, GitHub, using OAuth 2.0 protocol.
Best Practices
- Always hash and verify passwords (with
password_hash()). - Use HTTPS to secure credential transmission.
- Regenerate session IDs after login to avoid fixation attacks.
144 What are CSRF tokens and how are they implemented in PHP?
What are CSRF tokens and how are they implemented in PHP?
CSRF (Cross-Site Request Forgery) is an attack where a user is tricked into executing unwanted actions while authenticated. CSRF tokens prevent this by validating that form submissions originate from the same site.
How It Works
- Server generates a random, unique token.
- Token is embedded in each form (hidden input).
- On form submission, server checks if token matches the session token.
Example in Plain PHP
// Generate token
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// In HTML Form
<input type="hidden" name="csrf_token" value="= $_SESSION['csrf_token']; ?>" />
// Validation
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('Invalid CSRF token');
}Frameworks
- Laravel: CSRF is enabled by default in middleware.
- Symfony: Provides CSRF protection in forms.
Best Practice: Always use CSRF tokens for POST/PUT/DELETE requests that modify state. Combine with HTTPS and SameSite cookies for better security.
145 What is the difference between include_path and autoload in PHP?
What is the difference between include_path and autoload in PHP?
include_path and autoload are two mechanisms to manage file inclusion in PHP, but they serve different purposes.
include_path
- A PHP configuration directive (set in
php.inior usingset_include_path()). - Defines folders where PHP searches when using
includerequire, etc. - Static approach – developer must manually include required files.
set_include_path(get_include_path() . PATH_SEPARATOR . '/var/www/includes');
require 'config.php';Autoload
- Introduced to reduce manual
includecalls. - Automatically loads a class when it’s first referenced.
- Implemented via
spl_autoload_register()or Composer’s PSR-4 autoloader.
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.php';
});
$obj = new User(); // User.php automatically includedComparison
| Aspect | include_path | Autoload |
|---|---|---|
| Type | Config setting | Dynamic mechanism |
| Usage | Search path for includes | Loads classes automatically |
| Modern Use | Legacy/manual projects | Standard in frameworks (PSR-4) |
Best Practice: Use autoloading (via Composer PSR-4) in modern applications. include_path is mostly used in legacy environments.
146 How can PHP be integrated with front-end frameworks?
How can PHP be integrated with front-end frameworks?
Modern applications often separate frontend and backend. PHP typically acts as the backend (business logic, database) while JS frameworks handle the frontend presentation layer.
Integration Approaches
- Traditional: PHP renders HTML templates (Blade, Twig) and includes Vue/React components via CDN.
- API Driven: PHP provides REST APIs or GraphQL endpoints returning JSON, while frontend frameworks (React, Vue, Angular) consume them.
- Full-stack frameworks: Laravel Jetstream + Vue/React, Symfony + Vue integration bundles.
REST Integration Example
// Laravel Controller
return response()->json(User::all());// React fetch example
fetch('/api/users').then(res => res.json()).then(data => console.log(data));Best Practices
- Use CORS headers for cross-domain requests.
- Secure APIs with authentication (JWT, OAuth).
- Version your APIs (v1, v2).
147 How do PHP frameworks handle routing?
How do PHP frameworks handle routing?
Routing is the process of mapping incoming HTTP requests (URLs) to controller actions or functions. PHP frameworks provide routing systems for clean URLs and RESTful APIs.
Laravel Example
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::get('/users/{id}', [UserController::class, 'show']);Symfony Example
// config/routes.yaml
users_list:
path: /users
controller: App\Controller\UserController::indexRouting Features
- Named routes for easier redirects.
- Parameter constraints (e.g., numeric IDs).
- Middleware (auth, logging, throttling) applied to routes.
- RESTful resource routing.
Best Practice: Keep routes RESTful and descriptive. Use middleware for cross-cutting concerns like authentication and rate limiting.
148 What are virtual hosts and why are they important for PHP deployment?
What are virtual hosts and why are they important for PHP deployment?
Virtual hosts (Apache) or server blocks (Nginx) allow running multiple websites or PHP applications on a single server by mapping domains to specific directories.
Benefits
- Host multiple domains/subdomains on one server.
- Isolate different PHP projects.
- Customize configurations per site (PHP version, SSL, logging).
Apache Example
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example/public
</VirtualHost>Nginx Example
server {
server_name example.com;
root /var/www/example/public;
index index.php;
}Best Practice: Configure SSL/TLS for each virtual host, set proper permissions, and disable directory listing for security.
149 How can containerization be utilized for PHP applications?
How can containerization be utilized for PHP applications?
Containerization packages applications with their dependencies and environment configurations so they run consistently across systems. Tools like Docker are widely used for PHP apps.
Benefits
- Eliminates “works on my machine” problems.
- Provides isolation of apps.
- Enables efficient scaling via container orchestration (Kubernetes, Docker Swarm).
Example Dockerfile
FROM php:8.1-apache
WORKDIR /var/www/html
COPY . .
RUN docker-php-ext-install pdo pdo_mysql
EXPOSE 80
CMD ["apache2-foreground"]Best Practice
- Use Docker Compose for multi-service setups (app + DB + cache).
- Keep images small by using alpine-based images.
- Integrate into CI/CD pipelines for reproducibility.
150 What are htaccess files and their role in PHP?
What are htaccess files and their role in PHP?
.htaccess is a configuration file for the Apache web server that allows per-directory settings without modifying the main server configuration.
Role in PHP Applications
- URL rewriting – redirect requests to index.php for clean URLs (important for frameworks like Laravel, CodeIgniter).
- Access control – restrict access to directories or files.
- Security headers – enforce HSTS, disable directory listing.
- Custom error pages – display user-friendly error.html.
Example
# Redirect all requests to index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]Best Practices
- Use .htaccess only when you cannot access server config – it has performance cost.
- For production, prefer VirtualHost/ServerBlock configurations.
Conclusion: .htaccess files are essential for routing, access control, and deployment customization in Apache-powered PHP apps.
Unlock All Answers
Subscribe to get unlimited access to all 150 answers in this module.
Subscribe NowNo questions found
Try adjusting your search terms.