php
PHP is a widely used, server-side scripting language designed primarily for building dynamic and interactive web applications. It can be embedded directly into HTML and works with databases, web servers, and various development frameworks to create applications ranging from simple websites to large-scale platforms. Its straightforward syntax, extensive ecosystem, and broad hosting support have made PHP an important technology in web development.
This section explores the fundamental concepts of PHP, including variables, data types, operators, control structures, functions, arrays, classes, objects, error handling, and database connectivity. It also examines PHP’s key features, strengths, limitations, popular frameworks, and practical applications, providing a foundation for understanding how PHP is used to develop dynamic and database-driven web applications.

Introduction To php
Content Overview
- Learn PHP with AI Made Easy
- Introduction
- Detailed Setup and First Application
- 2.1 Prerequisites for Environment Setup
- 2.2 Linux Command-Line Environment
- 2.3 Linux Professional IDE Environment
- 2.4 Linux AI-Integrated Workflow
- 2.5 Windows Command-Line Environment
- 2.6 Windows Professional IDE Environment
- 2.7 Windows AI-Integrated Workflow
- 2.8 macOS Command-Line Environment
- 2.9 macOS Professional IDE Environment
- 2.10 macOS AI-Integrated Workflow
- 2.11 Built-in PHP Server & CLI Usage
- 2.12 Software Execution Lifecycle
- AI Integration with PHP
- PHP Fundamentals
- Functions
- Arrays & Superglobals
- Forms & User Input
- Object-Oriented Programming
- 8.1 Classes & Objects
- 8.2 Visibility (public, private, protected)
- 8.3 Constructors & Destructors
- 8.4 Inheritance
- 8.5 Polymorphism (Method Overriding)
- 8.6 Encapsulation & Abstraction
- 8.7 Interfaces & Traits
- 8.8 Static Members & Late Static Binding
- 8.9 Magic Methods (__get, __set, __call, __toString, etc.)
- 8.10 Namespaces & PSR-4 Autoloading
- 8.11 Dependency Injection & Design Patterns
- Databases & PDO
- Security
- File Handling & Error Handling
- Composer & Package Management
- REST APIs & Web Services
- Modern PHP (8.x Features)
- Laravel Framework
- Testing
- Performance Optimization
- Deployment & Production Architecture
- Real-World Projects
- Career Readiness
Learn PHP with AI Made Easy
Understanding PHP and Its Industry Importance
PHP (Hypertext Preprocessor) is one of the most widely used server-side programming languages for web development. It powers millions of websites, APIs, content management systems, e-commerce platforms, and enterprise applications. Popular platforms such as WordPress, Laravel, and Drupal are built using PHP.
PHP remains highly relevant because it is easy to learn, fast to deploy, and capable of powering applications ranging from simple websites to large-scale cloud platforms. Modern PHP has evolved significantly with features such as object-oriented programming, namespaces, dependency injection, attributes, strong typing, asynchronous processing integrations, and modern frameworks.
When a user visits a website, the following flow occurs:
- Browser sends request
- Web server receives request
- PHP executes on the server
- Database operations occur if needed
- HTML/JSON response is generated
- Browser receives final output
Unlike JavaScript, which often runs inside browsers, PHP executes on the server before content reaches users.
Major PHP use cases include:
- Dynamic websites
- E-commerce platforms
- REST APIs
- SaaS products
- CMS systems
- Enterprise applications
- CRM systems
- ERP systems
- Backend services
- Microservices
Career Relevance and Market Demand
PHP developers work in various roles including PHP Developer, Backend Developer, Full Stack Developer, Laravel Developer, WordPress Developer, API Developer, Software Engineer, and Solutions Architect. Many startups and enterprises continue to use PHP because of its mature ecosystem and cost-effective deployment.
Technical Prerequisites
Before learning PHP, it helps to understand basic computer skills, internet fundamentals, HTML basics, basic CSS, basic databases, and problem-solving skills. No prior programming experience is required.
Common Beginner Mistakes
Many beginners skip PHP fundamentals and jump directly into frameworks, ignore server concepts, learn syntax without understanding HTTP, avoid databases initially, neglect security practices, and ignore error handling and debugging.
Role of AI in PHP Development
AI significantly improves PHP development workflows. Developers use AI for code generation, API development, SQL query generation, refactoring, debugging, security reviews, performance optimization, documentation generation, unit testing, and architecture planning.
How to Use This Course Effectively
The best learning process is to learn a topic, build examples manually, study the code examples provided in each section, compare multiple solutions, build projects, debug with AI assistance, and optimize and refactor code. Each subtopic contains a Code Example block that demonstrates the concept with real PHP code. Copy that code into your environment, run it, and observe the expected output.
Introduction
1.1 What is PHP
PHP (Hypertext Preprocessor) is a server-side scripting language used to build dynamic websites and APIs. It runs on the server, generating HTML or JSON that is sent to the client
PHP is embedded within HTML and executed on the server before the page is sent to the browser. This allows for dynamic content generation, database interaction, file manipulation, and form processing. PHP is open-source, free to use, and has a massive ecosystem of frameworks and libraries. It’s particularly known for its ease of use, rapid development capabilities, and extensive documentation.
Code Example
<?php
echo "Hello, PHP!";
?>
Expected Output: Hello, PHP!
The <?php tag begins PHP code execution.The echo statement outputs text or other values as part of the response sent to the browser.The ?> tag ends the PHP block. When a user requests this page, the server processes the PHP code and sends only the output to the browser.
1.2 History of PHP
PHP was created by Rasmus Lerdorf in 1994 as a small tool to track visitors to his personal website. Originally named Personal Home Page Tools, it evolved into a full programming language.
PHP 5 (2004) brought strong OOP support, PDO for database abstraction, and exception handling. PHP 7 (2015) delivered a 2x performance boost, scalar type hints, null coalescing operator (??), and spaceship operator (<=>). PHP 8 (2020) introduced union types, attributes, match expression, nullsafe operator, constructor property promotion, and JIT compiler. PHP 8.1, 8.2, and 8.3 added enums, readonly properties, fibers, and improved type safety.
Code Example
<?php
// PHP 7+ null coalescing operator
$username = $_GET['user'] ?? 'Guest';
echo $username;
// PHP 8+ match expression
$statusCode = 200;
$message = match($statusCode) {
200 => "OK",
404 => "Not Found",
default => "Unknown"
};
echo "\n" . $message;
?>
Expected Output:
- If URL contains
?user=Zaigham:Zaigham - Otherwise:
Guest - Then:
OK
The null coalescing operator (??) checks if $_GET['user'] exists and is not null. If it does, it uses that value; otherwise, it uses the default 'Guest'. The match expression evaluates $statusCode and returns the corresponding string, providing a more concise alternative to switch statements.
1.3 Evolution of PHP Versions
PHP has evolved through several major versions, each bringing significant improvements in performance, type safety, and developer experience.
PHP 5 established modern OOP support, making PHP a serious enterprise language. PHP 7 dramatically improved performance and introduced scalar type hints, making code more reliable. PHP 8 modernized the language with union types, attributes, match expressions, and the nullsafe operator, making PHP code cleaner and more expressive.
Code Example
<?php
// PHP 8 union types - function accepts either int or string
function process(int|string $data): int|string {
return $data;
}
echo process(10) . "\n";
echo process("PHP");
?>
Expected Output:
10
PHP
Union types allow a parameter or return value to accept multiple types. In this example, process() accepts either an integer or a string and returns the same type. This provides flexibility while maintaining type safety.
1.4 PHP Runtime Architecture
PHP runs on the Zend Engine, which is the core execution engine. PHP is not a standalone server; it requires a web server like Apache or Nginx, or can run via built-in server for development.
The typical flow is: Browser → Web Server → PHP-FPM/Zend Engine → Database → Response. The Zend Engine parses PHP code, compiles it to opcode, and executes it. PHP-FPM (FastCGI Process Manager) handles multiple PHP requests efficiently. The built-in PHP server is suitable for development and testing.
Code Example
<?php
echo "Request received and processed by PHP";
?>
Expected Output: Request received and processed by PHP
When a request arrives, the web server passes it to PHP-FPM, which executes the script through the Zend Engine. The output is then returned to the web server and sent back to the client.
1.5 Request Lifecycle
The request lifecycle describes the journey of a request from the client to the server and back, including PHP processing.
- Client sends HTTP request
- Web server receives request
- PHP interpreter loads the script
- Code is parsed, compiled to opcode, and executed
- Output (HTML/JSON) is sent back to client
- Memory is freed after each request
Code Example
<?php
$start = microtime(true);
sleep(1);
echo "Execution time: " . (microtime(true) - $start) . " seconds";
?>
Expected Output: Execution time: 1.00... seconds
microtime(true) returns the current timestamp in seconds. The script sleeps for 1 second, then calculates the elapsed time. This demonstrates the execution phase of the request lifecycle.
1.6 PHP Type System (Strict vs Loose)
PHP is loosely typed by default, meaning variables can change types automatically (type juggling). Strict types can be enabled with declare(strict_types=1); to enforce type safety.
Loose typing allows operations between different types, automatically converting them as needed. Strict typing requires exact type matches, preventing unexpected behavior and catching errors early. Strict mode is recommended for production code to improve reliability and maintainability.
Code Example
<?php
// Loose typing - automatic type juggling
function add($a, $b) {
return $a + $b;
}
echo "Loose: " . add("5", 10) . "\n";
// Strict typing - exact type matching
declare(strict_types=1);
function addStrict(int $a, int $b): int {
return $a + $b;
}
echo "Strict: " . addStrict(5, 10);
// echo addStrict("5", 10); // Fatal error
?>
Expected Output:
Loose: 15
Strict: 15
In loose mode, "5" is automatically converted to an integer. In strict mode, passing a string would cause a fatal error. Strict types enforce type safety and prevent subtle bugs.
1.7 Zend Engine & Execution Model
The Zend Engine is PHP’s core execution engine. It parses PHP code, converts it to opcode, and executes it. OPcache stores opcode in memory for faster subsequent requests.
PHP code goes through several stages: lexing (tokenization), parsing (building an abstract syntax tree), compilation (generating opcode), and execution (running opcode). OPcache caches compiled opcode in shared memory, eliminating the compilation step for subsequent requests and significantly improving performance.
Code Example
<?php
$a = 5;
$b = 10;
echo $a + $b;
?>
Expected Output: 15
The Zend Engine tokenizes the code, parses it into an AST, compiles it to opcode, and executes it. The result is returned to the client. With OPcache enabled, the compilation step is skipped on subsequent requests.
Detailed Setup and First Application
2.1 Prerequisites for Environment Setup
Recommended requirements: Ubuntu 24.04 LTS, Windows 10/11, or macOS Ventura or newer. 8 GB RAM, 20 GB free storage, stable internet connection, and Composer.
- Ubuntu 24.04 LTS is recommended for Linux users
- Windows 10/11 are supported with WSL or native PHP
- macOS Ventura or newer supports PHP via Homebrew
- 8 GB RAM ensures smooth development
- 20 GB storage accommodates projects and dependencies
- Composer is essential for PHP package management
Code Example
# Check system requirements
php -v
composer -v
Expected Output: Version information for PHP and Composer
These commands verify that PHP and Composer are installed and display their versions, confirming the environment is ready.
2.2 Linux Command-Line Environment
Setting up PHP on Linux using the command line is straightforward with the system package manager.
Linux distributions like Ubuntu have PHP in their official repositories. The apt package manager simplifies installation and updates. The PHP CLI (Command Line Interface) allows running PHP scripts directly from the terminal.
Code Example
# Install PHP
sudo apt update
sudo apt install php php-cli -y
# Verify installation
php -v
# Create and run a PHP script
echo '<?php echo "Hello Linux"; ?>' > index.php
php index.php
Expected Output:
PHP version info...
Hello Linux
sudo apt update refreshes the package list. sudo apt install php php-cli installs PHP and CLI. php -v displays version info. The echo command creates a PHP file, and php index.php executes it.
2.3 Linux Professional IDE Environment
Using VS Code with PHP extensions provides a professional development environment on Linux.
VS Code is a free, lightweight editor with excellent PHP support. Installing PHP extensions provides syntax highlighting, IntelliSense, debugging, and integration with Xdebug. This environment is suitable for professional development.
Code Example
<?php
echo "Hello from VS Code";
?>
Expected Output: Hello from VS Code
Open VS Code, install the PHP extension, create a new file with the .php extension, write PHP code, and run it using the built-in terminal with php filename.php. VS Code provides autocomplete, error checking, and debugging capabilities.
2.4 Linux AI-Integrated Workflow
AI tools like GitHub Copilot can assist with PHP development, generating code snippets, suggesting completions, and providing intelligent assistance.
AI assistants analyze your code context and suggest completions, generate boilerplate code, and help with complex logic. They can be integrated into VS Code through extensions and significantly speed up development.
Code Example
<?php
// AI-generated calculator function
function add($a, $b) {
return $a + $b;
}
echo add(5, 3);
?>
Expected Output: 8
The AI assistant generates the function based on context. The developer can accept, modify, or reject suggestions. This accelerates development while maintaining code quality.
2.5 Windows Command-Line Environment
PHP can be installed on Windows using package managers like winget or by manual download.
Windows users can install PHP through package managers like winget, Chocolatey, or directly from php.net. The command line (PowerShell or Command Prompt) provides access to PHP CLI for running scripts.
Code Example
# Install PHP with winget
winget install PHP.PHP
# Verify installation
php -v
# Create and run a PHP script
echo ^<?php echo "Hello Windows"; ?^> > index.php
php index.php
Expected Output:
PHP version info...
Hello Windows
winget install PHP.PHP downloads and installs PHP. php -v verifies installation. The echo command creates a PHP file, and php index.php executes it.
2.6 Windows Professional IDE Environment
VS Code on Windows provides a professional PHP development environment with the same capabilities as on Linux.
VS Code on Windows functions identically to the Linux version. With PHP extensions installed, it provides syntax highlighting, debugging, and integration with Xdebug for step-by-step debugging.
Code Example
<?php
echo "Hello from VS Code on Windows";
?>
Expected Output: Hello from VS Code on Windows
Open VS Code, install the PHP extension, create a .php file, write code, and run it with php filename.php in the integrated terminal.
2.7 Windows AI-Integrated Workflow
AI assistants integrated with VS Code on Windows provide similar capabilities as on Linux, helping with PHP development.
GitHub Copilot and other AI assistants work seamlessly in VS Code on Windows. They provide code completion, bug detection, and refactoring suggestions tailored to PHP.
Code Example
<?php
// AI-generated secure form handling
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = htmlspecialchars($_POST['name']);
echo "Hello $name";
}
?>
Expected Output: When form submitted with name Zaigham, outputs Hello Zaigham
The AI suggests code for secure form handling, including input validation and sanitization. The developer reviews and integrates the code into their project.
2.8 macOS Command-Line Environment
PHP can be installed on macOS using Homebrew, a popular package manager for Mac.
Homebrew simplifies installing PHP and other development tools on macOS. The PHP CLI is then available for running scripts from the terminal.
Code Example
# Install PHP with Homebrew
brew install php
# Verify installation
php -v
# Create and run a PHP script
echo '<?php echo "Hello macOS"; ?>' > index.php
php index.php
Expected Output:
PHP version info...
Hello macOS
brew install php downloads and installs PHP. php -v verifies installation. The echo command creates a PHP file, and php index.php executes it.
2.9 macOS Professional IDE Environment
VS Code on macOS provides the same professional development environment as on other platforms.
VS Code for macOS supports PHP development with full IntelliSense, debugging, and Xdebug integration. The environment is identical to other platforms, ensuring consistent development experience.
Code Example
<?php
echo "Hello from VS Code on macOS";
?>
Expected Output: Hello from VS Code on macOS
Open VS Code, install the PHP extension, create a .php file, write code, and run it with php filename.php in the terminal.
2.10 macOS AI-Integrated Workflow
AI tools integrated with VS Code on macOS provide intelligent coding assistance for PHP development.
AI assistants help with code completion, generate boilerplate code, suggest fixes, and provide intelligent refactoring suggestions. They integrate seamlessly with the development workflow.
Code Example
<?php
// AI-generated fix for undefined variable
$name = $_POST['name'] ?? 'Guest';
echo $name;
?>
Expected Output: If $_POST['name'] is not set, prints Guest
The AI suggests using the null coalescing operator to handle missing POST data safely. The developer accepts the suggestion, making the code more robust.
2.11 Built-in PHP Server & CLI Usage
PHP includes a built-in web server that can be used to run and test PHP applications locally during development. The CLI provides a way to run PHP scripts from the command line.
The built-in server (php -S) starts a development server on localhost, ideal for testing without a full web server setup. CLI scripts can accept arguments and output results directly in the terminal.
Code Example
# Start built-in server
php -S localhost:8000
# CLI - execute code directly
php -r "echo 5+5;"
# CLI - lint syntax
php -l index.php
# CLI script with arguments
php app.php Zaigham
Expected Output:
10
No syntax errors detected
Hello Zaigham
The built-in server hosts files from the current directory. php -r executes code directly. php -l checks for syntax errors. CLI scripts accept command-line arguments in $argv.
2.12 Software Execution Lifecycle
The software execution lifecycle describes how a PHP application processes a request and generates a response.
The lifecycle includes request reception, PHP processing, database operations, output generation, and response delivery. Each step contributes to the final output sent to the client.
Code Example
<?php
echo "Step 1: Client request\n";
echo "Step 2: PHP processing\n";
echo "Step 3: Database operations (if needed)\n";
echo "Step 4: Response generated\n";
?>
Expected Output:
Step 1: Client request
Step 2: PHP processing
Step 3: Database operations (if needed)
Step 4: Response generated
Each echo statement represents a step in the lifecycle. The script demonstrates the sequential flow from request reception to response generation.
AI Integration with PHP
3.1 AI-Assisted Coding
AI-assisted coding uses machine learning models to help developers write code faster and with fewer errors.
AI tools like GitHub Copilot analyze your code context and suggest completions, generate entire functions, and provide intelligent code snippets. This accelerates development by reducing boilerplate code and suggesting best practices.
Code Example
<?php
// AI-generated email validation
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
echo isValidEmail("test@example.com") ? "Valid" : "Invalid";
?>
Expected Output: Valid
The AI generates a function that validates email addresses using PHP’s built-in filter. The developer reviews and uses the generated code, saving time on writing validation logic.
3.2 AI Debugging
AI debugging helps identify and fix issues in PHP code by analyzing error messages and suggesting solutions.
AI tools can read error messages, identify the root cause, and suggest fixes. They can also detect potential bugs before they occur by analyzing code patterns and suggesting improvements.
Code Example
<?php
// Buggy code (commented out)
// echo $undefined_var;
// AI suggestion - define the variable
$undefined_var = "value";
echo $undefined_var;
?>
Expected Output: value
The AI detects the undefined variable and suggests defining it. The developer follows the suggestion, fixing the bug. This accelerates debugging and learning from errors.
3.3 AI Security Analysis
AI security analysis examines PHP code for vulnerabilities and suggests secure alternatives.
AI tools can detect SQL injection vulnerabilities, XSS risks, CSRF vulnerabilities, and other security issues. They suggest secure coding practices and generate secure code alternatives.
Code Example
<?php
// AI-generated secure prepared statement
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => $_GET['id']]);
?>
Expected Output: No SQL injection vulnerability
The AI generates a prepared statement that prevents SQL injection. The developer uses this secure code instead of concatenating user input directly into SQL queries.
3.4 AI Documentation Generation
AI can generate documentation comments for PHP functions, classes, and methods automatically.
AI tools analyze function signatures and generate PHPDoc comments describing parameters, return values, and purpose. This improves code documentation and makes it easier for other developers to understand the code.
Code Example
<?php
/**
* Calculates the sum of two numbers.
*
* @param int $a First number
* @param int $b Second number
* @return int The sum
*/
function sum(int $a, int $b): int {
return $a + $b;
}
echo sum(2, 3);
?>
Expected Output: 5
The AI generates PHPDoc comments that document the function’s purpose, parameters, and return type. This documentation helps other developers understand and use the function correctly.
3.5 AI Testing Assistance
AI can generate unit tests for PHP code, ensuring code reliability and catching bugs early.
AI tools analyze functions and generate test cases covering various scenarios, including edge cases. This helps developers write comprehensive tests faster and achieve higher code coverage.
Code Example
<?php
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase {
public function testAdd() {
$calc = new Calculator();
$this->assertEquals(5, $calc->add(2, 3));
}
}
?>
Expected Output: Test passes
The AI generates a PHPUnit test class with a test method. The test verifies that the add() function returns the correct result. Automated testing ensures code quality.
3.6 AI Refactoring Workflows
AI refactoring helps improve code quality by suggesting cleaner, more efficient alternatives.
AI tools can suggest improvements like converting loops to functional constructs, simplifying conditionals, and improving code readability. They preserve functionality while enhancing code quality.
Code Example
<?php
$numbers = [1, 2, 3, 4];
// Before refactoring (commented)
/*
$squared = [];
for ($i = 0; $i < count($numbers); $i++) {
$squared[] = $numbers[$i] * $numbers[$i];
}
*/
// After refactoring - more concise
$squared = array_map(fn($n) => $n * $n, $numbers);
print_r($squared);
?>
Expected Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )
The AI suggests using array_map() with an arrow function instead of a loop. This makes the code more concise and expressive while achieving the same result.
PHP Fundamentals
4.1 PHP Syntax (Tags, echo/print, Comments)
PHP syntax includes opening/closing tags, output statements, and comments that make code self-documenting.
Opening and closing tags <?php ?> enclose PHP code. echo outputs multiple values and is slightly faster. print outputs a single value and returns 1. Comments include // for single-line, /* */ for multi-line, and # for single-line (less common).
Code Example
<?php
// Single-line comment
echo "Hello "; // Outputs text, faster than print
print "World\n"; // Outputs text, returns 1
/*
Multi-line comment
for longer explanations
*/
?>
Expected Output:
Hello World
The echo and print statements send output to the browser. echo can output multiple values separated by commas. print always returns 1. Comments are ignored by the PHP interpreter and only visible in the source code.
4.2 Variables & Constants
define vs const, magic constants, variable variables
Variables store data that can change. Constants store fixed values. Magic constants provide information about the current script. Variable variables allow dynamic variable names.
Variables start with $ and are case-sensitive. Constants are defined with define() (runtime) or const (compile-time). Magic constants like __LINE__, __FILE__, __DIR__ provide context information. Variable variables ($$varName) allow dynamic variable creation.
Code Example
<?php
// Variable
$name = "Zaigham";
// Constants
define("SITE_NAME", "MySite");
const VERSION = "1.0";
// Magic constant
echo __LINE__ . "\n"; // Current line number
// Variable variable
$varName = "message";
$$varName = "Hello"; // Creates $message = "Hello"
echo $message;
?>
Expected Output:
(Line number)
Hello
Variables store values that can change. Constants are fixed throughout execution. Magic constants are resolved by the interpreter. Variable variables create new variables dynamically based on string values.
4.3 Data Types
Scalar, Compound, Special, Union Types
PHP supports several data types including scalar, compound, special, and union types.
Scalar types include int, float, string, and bool. Compound types include array, object, and callable. Special types include null and resource. Union types (PHP 8+) allow multiple types. PHP is dynamically typed, meaning types are checked at runtime.
Code Example
<?php
$int = 10; // Integer
$float = 3.14; // Float
$string = "PHP"; // String
$bool = true; // Boolean
$array = [1, 2, 3]; // Array
$null = null; // Null
// Union type (PHP 8+)
function process(int|string $value): int|string {
return $value;
}
echo process(42);
?>
Expected Output: 42
Variables are assigned values of different types. The process() function accepts either an integer or string and returns the same type. The type is checked at runtime.
4.4 Operators
Arithmetic, Assignment, Comparison, Logical, etc.
Operators perform operations on variables and values, enabling calculations, comparisons, and logical decisions.
Arithmetic operators (+, -, *, /, %, **) perform mathematical calculations. Assignment operators (=, +=, -=, etc.) assign values. Comparison operators (==, ===, !=, !==, <, >, <=, >=) compare values. Logical operators (&&, ||, !) combine boolean conditions. Null coalescing (??) provides default values.
Code Example
<?php
$a = 10;
$b = 3;
// Arithmetic
echo $a + $b . "\n"; // 13
echo $a - $b . "\n"; // 7
echo $a * $b . "\n"; // 30
echo $a / $b . "\n"; // 3.3333333333333
echo $a % $b . "\n"; // 1
echo $a ** $b . "\n"; // 1000
// Assignment
$a += 5; // $a = $a + 5
// Comparison
var_dump($a == "15"); // true (loose)
var_dump($a === 15); // true (strict)
// Null coalescing
$c = $a ?? "default";
echo $c;
?>
Expected Output:
13
7
30
3.3333333333333
1
1000
bool(true)
bool(true)
15
Operators follow standard precedence rules. == checks equality after type juggling, while === checks both value and type. The null coalescing operator ?? returns the first non-null value.
4.5 Type Casting & Strict Types
Type casting converts values from one type to another. Strict types enforce exact type matching.
Type casting uses syntax like (int), (float), (string) to convert values. Strict types with declare(strict_types=1); prevent automatic type juggling, requiring exact type matches. This catches errors early and improves code reliability.
Code Example
<?php
// Type casting
$num = "123";
$intNum = (int)$num;
echo $intNum . "\n"; // 123
// Strict types
declare(strict_types=1);
function square(int $x): int {
return $x * $x;
}
echo square(5); // 25
// echo square("5"); // Fatal error
?>
Expected Output:
123
25
The (int) cast converts a string to an integer. With strict types enabled, function arguments must match exactly. Passing a string to an int parameter causes a fatal error, preventing subtle bugs.
4.6 Control Structures
if, switch, match, loops, break/continue
Control structures direct the flow of program execution based on conditions and iterations.
if statements execute code based on conditions. switch tests a variable against multiple values. match (PHP 8+) is a stricter, more expressive alternative to switch. Loops (for, while, foreach) repeat code blocks. break exits a loop, continue skips to the next iteration.
Code Example
<?php
// if statement
$age = 18;
if ($age >= 18) {
echo "Adult\n";
} else {
echo "Minor\n";
}
// switch
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start week\n";
break;
default:
echo "Other\n";
}
// match (PHP 8+)
$status = 200;
$message = match($status) {
200 => "OK",
404 => "Not Found",
default => "Unknown"
};
echo $message . "\n";
// for loop
for ($i = 0; $i < 3; $i++) {
echo $i;
}
?>
Expected Output:
Adult
Start week
OK
012
if evaluates a condition and executes the corresponding block. switch compares the variable to each case. match returns a value based on the matched condition. for repeats the block while the condition is true.
Functions
5.1 Function Declaration & Parameters
Functions are reusable blocks of code that perform specific tasks. Parameters pass data into functions.
Functions in PHP are declared using the function keyword. Parameters are variables defined in the function’s declaration, while arguments are the actual values supplied when the function is called. Functions can accept multiple parameters and use return to send a value back to the caller.
Code Example
<?php
function greet($name) {
return "Hello $name";
}
echo greet("Zaigham");
?>
Expected Output: Hello Zaigham
The greet() function accepts a $name parameter and returns a greeting string. When called with "Zaigham", it returns "Hello Zaigham".
5.2 Return Types & Type Declarations
Return types specify what type of value a function returns. Type declarations enforce parameter types.
Type declarations specify expected parameter types. Return types specify the type of value a function returns. Both improve code reliability and self-documentation. Strict types must be enabled to enforce them.
Code Example
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
echo add(5, 10);
?>
Expected Output: 15
The add() function requires two integers and returns an integer. The int type declarations enforce these requirements, catching type errors at runtime.
5.3 Named Arguments (PHP 8+)
Named arguments allow calling functions with arguments in any order by specifying parameter names.
Named arguments improve code readability and reduce errors by explicitly stating which argument corresponds to which parameter. They allow skipping default arguments and reordering arguments as needed.
Code Example
<?php
function createUser($name, $age, $role = "user") {
return "$name, $age, $role";
}
// Named arguments - order doesn't matter
echo createUser(age: 30, name: "Zaigham", role: "admin");
?>
Expected Output: Zaigham, 30, admin
Named arguments specify the parameter name followed by a colon and the argument value. This allows calling the function with arguments in any order and ignoring parameters with default values.
5.4 Anonymous Functions & Closures
Anonymous functions are functions without a name. Closures capture variables from the surrounding scope.
Anonymous functions are defined using function() syntax without a name. Closures capture variables from the parent scope using the use keyword. They are often used as callbacks and for functional programming.
Code Example
<?php
// Anonymous function
$greet = function($name) {
return "Hello $name";
};
echo $greet("World") . "\n";
// Closure with use
$prefix = "Hello";
$greetWithPrefix = function($name) use ($prefix) {
return "$prefix $name";
};
echo $greetWithPrefix("PHP");
?>
Expected Output:
Hello World
Hello PHP
The anonymous function is assigned to a variable and called like a regular function. The closure uses use to capture $prefix from the outer scope, making it available inside the function.
5.5 Arrow Functions (PHP 7.4+)
Arrow functions provide a shorter syntax for simple anonymous functions using fn.
Arrow functions are concise one-liners that automatically capture variables from the parent scope. They cannot contain multiple statements or complex logic. They’re ideal for simple transformations and functional programming.
Code Example
<?php
$numbers = [1, 2, 3, 4];
$squared = array_map(fn($n) => $n * $n, $numbers);
print_r($squared);
?>
Expected Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )
The arrow function fn($n) => $n * $n squares each element. It automatically captures the $numbers variable from the parent scope. The result is a new array with squared values.
5.6 Recursive Functions
Recursive functions call themselves to solve problems by breaking them into smaller, similar subproblems.
Recursion involves a function calling itself. A base case stops the recursion. Recursive cases break the problem down further. Recursion is useful for problems with repeated structures like tree traversal and mathematical operations.
Code Example
<?php
function factorial($n) {
if ($n <= 1) { // Base case
return 1;
}
return $n * factorial($n - 1); // Recursive case
}
echo factorial(5);
?>
Expected Output: 120
factorial(5) calls factorial(4), which calls factorial(3), and so on until factorial(1) returns 1. The results are then multiplied back up the chain: 5 × 4 × 3 × 2 × 1 = 120.
5.7 Generators (yield)
Generators allow yielding multiple values without storing an entire array in memory.
Generators use the yield keyword to produce values one at a time, allowing the caller to process each value as it is generated rather than creating all values at once. The function’s state is preserved between calls. This is memory-efficient for large datasets. Generators return an iterable that can be used with foreach.
Code Example
<?php
function numbers($max) {
for ($i = 1; $i <= $max; $i++) {
yield $i; // Yield one value at a time
}
}
foreach (numbers(5) as $n) {
echo $n;
}
?>
Expected Output: 12345
The numbers() generator yields values one by one. Each foreach iteration requests the next value, and the generator resumes from where it paused. This avoids storing all values in memory at once.
5.8 Attributes (PHP 8+)
Attributes provide metadata for classes, methods, properties, and functions using the #[...] syntax.
Attributes are structured metadata that can be read at runtime using reflection. They replace PHPDoc annotations in many cases. Attributes can be used for routing, validation, serialization, and more.
Code Example
<?php
#[Route("/users")]
function getUsers() {
return ["Alice", "Bob"];
}
$reflection = new ReflectionFunction('getUsers');
foreach ($reflection->getAttributes() as $attr) {
echo $attr->getName(); // Outputs: Route
}
?>
Expected Output: Route
The #[Route("/users")] attribute attaches metadata to the function. Reflection reads this metadata at runtime. Attributes are strongly typed and can contain multiple parameters.
Arrays & Superglobals
6.1 Indexed, Associative & Multidimensional Arrays
Arrays store multiple values. Indexed arrays use numeric keys. Associative arrays use string keys. Multidimensional arrays contain other arrays.
Indexed arrays use automatic numeric keys starting from 0. Associative arrays use explicit keys for values. Multidimensional arrays contain arrays as elements, creating nested structures. Arrays are dynamic and can grow as needed.
Code Example
<?php
// Indexed array
$indexed = ["Apple", "Banana", "Cherry"];
// Associative array
$assoc = ["name" => "Zaigham", "age" => 30];
// Multidimensional array
$multi = [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 30]
];
echo $indexed[0] . "\n"; // Apple
echo $assoc["name"] . "\n"; // Zaigham
echo $multi[1]["name"] . "\n"; // Bob
?>
Expected Output:
Apple
Zaigham
Bob
Indexed arrays are accessed by numeric position. Associative arrays are accessed by string keys. Multidimensional arrays use multiple indices to access nested values.
6.2 Array Functions (map, filter, reduce, sorting)
Array functions transform, filter, and combine array elements in various ways.
array_map() applies a callback to each element. array_filter() filters elements based on a callback. array_reduce() reduces an array to a single value. sort() sorts arrays by value. These functions enable functional programming with arrays.
Code Example
<?php
$numbers = [1, 2, 3, 4, 5];
// Map - square each number
$squared = array_map(fn($n) => $n * $n, $numbers);
// Filter - keep even numbers
$evens = array_filter($numbers, fn($n) => $n % 2 == 0);
// Reduce - sum all numbers
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
echo "Squared: "; print_r($squared);
echo "Evens: "; print_r($evens);
echo "Sum: $sum\n";
// Sort
sort($numbers);
print_r($numbers);
?>
Expected Output:
Squared: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
Evens: Array ( [1] => 2 [3] => 4 )
Sum: 15
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
array_map() applies the arrow function to each element. array_filter() keeps elements where the callback returns true. array_reduce() accumulates values. sort() reorders the array in place.
6.3 Superglobals: $_GET, $_POST, $_REQUEST, $_SESSION, $_COOKIE, $_SERVER, $_FILES
Superglobals are predefined variables that provide access to request data, server information, and session state.
$_GET contains URL query parameters. $_POST contains form data sent with POST. $_REQUEST combines GET, POST, and COOKIE data. $_SESSION stores session data. $_COOKIE contains cookie data. $_SERVER contains server and request information. $_FILES contains uploaded files.
Code Example
<?php
session_start();
$_SESSION['user'] = 'Zaigham';
setcookie("theme", "dark", time() + 3600);
echo "GET id: " . ($_GET['id'] ?? 'none') . "\n";
echo "POST username: " . ($_POST['username'] ?? 'none') . "\n";
echo "Request method: " . $_SERVER['REQUEST_METHOD'] . "\n";
if (isset($_FILES['avatar'])) {
move_uploaded_file($_FILES['avatar']['tmp_name'], "uploads/" . $_FILES['avatar']['name']);
}
?>
Expected Output: Depends on request; shows superglobal values
Superglobals are automatically populated based on the request. $_GET retrieves URL parameters. $_POST retrieves form data. $_SESSION stores data across requests. $_SERVER provides request details. $_FILES handles file uploads.
6.4 Combining Arrays, Superglobals & Functions
Practical combination of arrays, superglobals, and functions for real-world applications.
This combines array functions with superglobals for data processing. Input is validated and sanitized, then processed using array functions. This is typical of request handling in web applications.
Code Example
<?php
function sanitize($data) {
return htmlspecialchars(trim($data));
}
$username = sanitize($_POST['username'] ?? '');
$colors = ["red", "green", "blue"];
if (in_array($username, $colors)) {
echo "Color found";
} else {
echo "Color not found";
}
?>
Expected Output: If $_POST['username'] is green, prints Color found
The sanitize() function trims whitespace and escapes HTML. The in_array() function checks if the submitted value exists in the colors array. This combines input handling with array operations.
Forms & User Input
7.1 Handling Forms (GET vs POST)
Forms collect user input. GET submits data in the URL. POST submits data in the request body.
GET appends data to the URL, visible in browser history. POST sends data in the request body, more secure for sensitive data. GET is suitable for searches. POST is suitable for data that modifies server state. Form data is accessed via $_GET or $_POST.
Code Example
<!-- HTML form -->
<form method="post" action="process.php">
<input name="username">
<input type="submit">
</form>
<?php
// process.php
$username = $_POST['username'] ?? '';
echo "Hello $username";
?>
Expected Output: Hello [entered name]
The form sends a POST request to process.php. PHP populates $_POST['username'] with the submitted value. The script echoes a greeting using the submitted name.
7.2 File Uploads
File uploads allow users to send files to the server via HTML forms.
File uploads require enctype="multipart/form-data" in the form. $_FILES contains file information. move_uploaded_file() moves the file to the desired location. Always validate file types and sizes for security.
Code Example
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$target = "uploads/" . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
echo "Uploaded successfully";
}
}
?>
Expected Output: Uploaded successfully if file is valid
The script checks if a file was uploaded. It then moves the temporary file to the target directory. move_uploaded_file() validates that the file was uploaded via PHP, providing security.
7.3 Data Validation & Sanitization
Validation ensures input meets criteria. Sanitization cleans input to prevent security issues.
Validation checks whether input meets the required rules or format, such as determining whether an email address is valid. Sanitization cleans input (e.g., remove HTML tags). PHP provides built-in filters for common validation and sanitization tasks. Never trust user input.
Code Example
<?php
$email = $_POST['email'] ?? '';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
$clean_name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
?>
Expected Output: Valid email if valid email provided
filter_var() with FILTER_VALIDATE_EMAIL checks email format. FILTER_SANITIZE_STRING removes HTML tags and special characters from the input.
7.4 Filter Functions (Built-in)
Built-in filter functions validate and sanitize input using PHP’s filter extension.
The filter extension provides numerous validation and sanitization filters. Validation filters check if data is valid (email, URL, IP, integer, etc.). Sanitization filters clean data (remove HTML, encode special characters). filter_input() can validate input directly.
Code Example
<?php
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, [
"options" => ["min_range" => 1, "max_range" => 100]
]);
if ($age) {
echo "Age is valid: $age";
} else {
echo "Invalid age";
}
?>
Expected Output: Age is valid: 25 if age=25 posted
filter_input() validates POST input using FILTER_VALIDATE_INT with min/max range options. It returns the validated integer or false if validation fails.
Object-Oriented Programming
8.1 Classes & Objects
Classes are blueprints for objects. Objects are instances of classes with properties and methods.
Classes define the structure and behavior. Objects are actual instances with their own data. Properties store data. Methods define behavior. Objects are created with new. Use $this to refer to the current object.
Code Example
<?php
class User {
public $name;
public function greet() {
return "Hello $this->name";
}
}
$user = new User();
$user->name = "Zaigham";
echo $user->greet();
?>
Expected Output: Hello Zaigham
The User class defines a $name property to store a user’s name and a greet() method that can use that name to produce a greeting. Creating a new instance and setting $name allows the method to access and use it.
8.2 Visibility (public, private, protected)
Visibility controls access to class properties and methods from different contexts.
public members are accessible from anywhere. private members are only accessible within the class. protected members are accessible within the class and subclasses. Encapsulation is achieved by using visibility modifiers.
Code Example
<?php
class Account {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
$acc = new Account();
$acc->deposit(100);
echo $acc->getBalance(); // 100
// echo $acc->balance; // Error: cannot access private
?>
Expected Output: 100
$balance is private, so it cannot be accessed directly. The deposit() and getBalance() methods provide controlled access, enforcing encapsulation.
8.3 Constructors & Destructors
Constructors initialize objects when they are created, while destructors perform cleanup when objects are destroyed.
Constructors (__construct()) are called automatically when an object is created and are typically used to initialize its properties. Destructors (__destruct()) are called when an object is destroyed and are used to perform necessary cleanup.
Code Example
<?php
class Product {
public $name;
public function __construct($name) {
$this->name = $name;
echo "Product $name created\n";
}
public function __destruct() {
echo "Product $this->name destroyed\n";
}
}
$p = new Product("Laptop");
?>
Expected Output:
Product Laptop created
Product Laptop destroyed
The constructor runs when the object is created. The destructor runs when the object goes out of scope or the script ends. This demonstrates resource management.
8.4 Inheritance
Inheritance allows a class to extend another class, inheriting its properties and methods.
Base class (parent) provides functionality. Derived class (child) extends the base class. Child classes can add new methods or override existing ones. parent:: calls parent methods. Inheritance promotes code reuse.
Code Example
<?php
class Animal {
public function speak() {
return "Animal sound";
}
}
class Dog extends Animal {
public function speak() {
return "Bark";
}
}
$dog = new Dog();
echo $dog->speak(); // Bark
?>
Expected Output: Bark
Dog extends Animal and overrides the speak() method. When speak() is called on $dog, the overridden version runs, demonstrating polymorphism.
8.5 Polymorphism (Method Overriding)
Polymorphism allows objects of different classes to be treated as the same type through method overriding.
Method overriding occurs when a child class provides its own implementation of a parent method. This enables polymorphism, where different objects respond to the same method call in different ways. Interfaces also enable polymorphism.
Code Example
<?php
class Shape {
public function area() {
return 0;
}
}
class Circle extends Shape {
private $radius;
public function __construct($r) {
$this->radius = $r;
}
public function area() {
return pi() * $this->radius * $this->radius;
}
}
$shapes = [new Circle(5)];
foreach ($shapes as $shape) {
echo $shape->area();
}
?>
Expected Output: 78.539816339745
Circle overrides area() to calculate its own area. The loop treats all shapes uniformly, but each object computes its area correctly.
8.6 Encapsulation & Abstraction
Encapsulation hides internal details. Abstraction shows only essential features.
Encapsulation bundles data and methods, hiding implementation with private/protected visibility. Abstraction provides simple interfaces while hiding complexity. Abstract classes and interfaces enforce abstraction.
Code Example
<?php
abstract class Vehicle {
abstract public function start();
}
class Car extends Vehicle {
public function start() {
return "Car started";
}
}
$car = new Car();
echo $car->start();
?>
Expected Output: Car started
The abstract Vehicle class defines a contract that all vehicles must implement. The concrete Car class provides the implementation, hiding the details of how the car starts.
8.7 Interfaces & Traits
Interfaces define contracts. Traits provide reusable code that can be shared across classes.
Interfaces declare methods that implementing classes must define. Multiple interfaces can be implemented. Traits provide reusable method implementations that can be used in multiple classes. Traits solve the problem of multiple inheritance.
Code Example
<?php
// Interface - defines contract
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
return "Log: $message";
}
}
// Trait - reusable code
trait Timestamp {
public function getTime() {
return date('Y-m-d H:i:s');
}
}
class Post {
use Timestamp;
}
$p = new Post();
echo $p->getTime();
?>
Expected Output: Current date and time (e.g., 2026-06-08 12:00:00)
The interface defines what methods must exist. The class implements them. Traits add methods to classes without inheritance. The Post class uses the Timestamp trait to get time functionality.
8.8 Static Members & Late Static Binding
Static members belong to the class, not objects. Late static binding resolves to the called class at runtime.
Static properties are shared across all instances. Static methods are called on the class, not objects. Late static binding (static::) resolves to the class at runtime, unlike self:: which resolves at compile time.
Code Example
<?php
class Counter {
public static $count = 0;
public static function increment() {
self::$count++;
}
}
Counter::increment();
echo Counter::$count; // 1
?>
Expected Output: 1
$count is static, shared by all instances. Counter::increment() increments the shared counter. Counter::$count accesses the static property directly.
8.9 Magic Methods (__get, __set, __call, __toString, etc.)
Magic methods are automatically called in certain situations, enabling dynamic behavior.
__get($key) handles undefined property reads. __set($key, $value) handles undefined property writes. __call($method, $args) handles undefined method calls. __toString() defines string representation. These enable dynamic property access and method calling.
Code Example
<?php
class Person {
private $data = [];
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function __get($key) {
return $this->data[$key] ?? null;
}
public function __toString() {
return $this->data['name'] ?? '';
}
}
$p = new Person();
$p->name = "Zaigham";
echo $p->name . "\n";
echo $p;
?>
Expected Output:
Zaigham
Zaigham
These magic methods handle access to properties that are not directly defined. They can store and retrieve values from an internal data array. The __toString() method is automatically called when an object is used where a string is expected.
8.10 Namespaces & PSR-4 Autoloading
Namespaces organize code and prevent naming conflicts. PSR-4 autoloading automatically loads classes.
Namespaces group code under logical names. They prevent collisions between different libraries. PSR-4 autoloading maps namespaces to directory structures. Composer handles autoloading automatically.
Code Example
// src/Models/User.php
<?php
namespace App\Models;
class User {}
?>
// composer.json
{
"autoload": {
"psr-4": {"App\\": "src/"}
}
}
// Usage
<?php
require 'vendor/autoload.php';
use App\Models\User;
$user = new User();
echo "User loaded";
?>
Expected Output: User loaded
The namespace identifies the logical location of a class within the application. With PSR-4 autoloading, a namespace such as App\ can be mapped to the src/ directory. Composer’s autoloader then automatically loads the corresponding class file when the class is first referenced.
8.11 Dependency Injection & Design Patterns
Dependency Injection provides dependencies from outside. Design Patterns are reusable solutions to common problems.
Dependency Injection (DI) provides a class with the objects or services it depends on instead of having the class create them internally. This promotes loose coupling, making the code easier to test, maintain, and modify.
Design patterns are reusable approaches to common software design problems. Examples include Singleton, Factory, and Repository patterns, each serving different design purposes.
Code Example
<?php
class Database {
public function connect() {
return "Connected";
}
}
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getConnection() {
return $this->db->connect();
}
}
$db = new Database();
$repo = new UserRepository($db);
echo $repo->getConnection();
?>
Expected Output: Connected
Database is injected into UserRepository through the constructor. This decouples the repository from the database creation, allowing easy substitution for testing.
Databases & PDO
9.1 MySQL Basics
MySQL is a relational database management system (RDBMS) commonly used with PHP applications to store, organize, and retrieve structured data.
MySQL organizes data into structured tables, where rows represent individual records and columns represent the attributes or fields of those records. PHP communicates with MySQL using extensions like mysqli or PDO. Basic operations include SELECT, INSERT, UPDATE, DELETE.
Code Example
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
?>
Expected Output: Array of rows from users table
mysqli_connect() establishes a database connection. mysqli_query() executes the SQL query. mysqli_fetch_assoc() fetches each row as an associative array until no more rows exist.
9.2 PDO (Prepared Statements, Transactions)
PDO (PHP Data Objects) provides a consistent interface for database access with security features.
PDO supports prepared statements, which prevent SQL injection. Transactions allow grouping multiple operations as a single unit. Error handling uses exceptions with ERRMODE_EXCEPTION. PDO works with multiple database drivers.
Code Example
<?php
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepared statement - prevents SQL injection
$stmt = $pdo->prepare("INSERT INTO users (name) VALUES (:name)");
$stmt->execute(['name' => 'Zaigham']);
// Query
$stmt = $pdo->query("SELECT * FROM users");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
// Transaction
$pdo->beginTransaction();
try {
$pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id=1");
$pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id=2");
$pdo->commit();
echo "Transaction committed";
} catch (Exception $e) {
$pdo->rollBack();
echo "Transaction failed: " . $e->getMessage();
}
?>
Expected Output: Rows from users table, then “Transaction committed” if successful
Prepared statements separate SQL from data, preventing injection. Transactions ensure all operations succeed or none take effect. Exceptions provide clear error handling.
9.3 Joins, Indexing, Query Optimization
Joins combine data from multiple tables. Indexing speeds up queries. Optimization improves performance.
Joins retrieve related data from multiple tables using foreign keys. Indexes speed up WHERE clause lookups. Optimization involves analyzing query performance with EXPLAIN, using proper indexes, and avoiding SELECT *.
Code Example
-- SQL Join Example (not executable directly in PHP)
SELECT users.name, orders.total
FROM users
JOIN orders ON users.id = orders.user_id;
-- Create index
CREATE INDEX idx_user_email ON users(email);
-- Analyze query
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
JOIN combines data based on relationships. Indexes create fast lookups for specific columns. EXPLAIN shows the query execution plan for optimization.
9.4 Stored Procedures & Migrations
Stored procedures are precompiled SQL routines. Migrations manage database schema changes.
Stored procedures are saved SQL code that can be called by PHP. They improve performance and encapsulate logic. Migrations track and apply database schema changes in a version-controlled way.
Code Example
-- Stored procedure
DELIMITER //
CREATE PROCEDURE GetUser(IN user_id INT)
BEGIN
SELECT * FROM users WHERE id = user_id;
END //
DELIMITER ;
<?php
// Calling stored procedure
$stmt = $pdo->prepare("CALL GetUser(:id)");
$stmt->execute(['id' => 1]);
$user = $stmt->fetch();
print_r($user);
?>
Expected Output: Array with user data for id=1
The stored procedure is created in MySQL. PHP calls it with CALL GetUser(:id). The procedure executes on the database server and returns results.
Security
10.1 SQL Injection Prevention
SQL injection attacks insert malicious SQL through user input. Prepared statements prevent this.
SQL injection occurs when user input is concatenated into SQL queries. Prepared statements separate SQL structure from data, preventing injection. Parameterized queries are the definitive protection against SQL injection.
Code Example
<?php
// Secure - prepared statement prevents injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $_POST['email']]);
$user = $stmt->fetch();
print_r($user);
?>
Expected Output: Safe query execution
The prepared statement sends the SQL and data separately. The database processes the SQL structure first, then applies data safely. Even if data contains malicious SQL, it can’t change the structure.
10.2 XSS Prevention
XSS (Cross-Site Scripting) injects JavaScript into web pages. HTML escaping prevents it.
XSS occurs when untrusted data is output to HTML. htmlspecialchars() converts special characters in a string into their corresponding HTML entities, helping prevent user-supplied content from being interpreted as executable HTML or JavaScript. Context-specific escaping (like JavaScript escaping) may be needed.
Code Example
<?php
// Escape output to prevent XSS
echo htmlspecialchars($_POST['comment']);
?>
Expected Output: Escaped HTML
htmlspecialchars() converts <, >, ", ', and & to HTML entities. This ensures that user input is treated as text, not executable code.
10.3 CSRF Protection
CSRF (Cross-Site Request Forgery) tricks users into making unwanted requests. Tokens prevent this.
CSRF exploits a user’s authenticated session. Protection uses unique tokens stored in session and form. The token must match to validate the request. The token should be regenerated for each session.
Code Example
<?php
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;
?>
<form method="post">
<input type="hidden" name="csrf_token" value="<?= $token ?>">
<input type="submit">
</form>
<?php
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("Invalid CSRF");
}
?>
Expected Output: Form submitted only with valid token
The server generates a token and stores it in session. The token is embedded in the form. When submitted, the server validates that the token matches the session token.
10.4 Password Hashing
Password hashing securely stores user passwords using one-way algorithms.
password_hash() creates a secure hash using bcrypt or Argon2. password_verify() verifies a password against a hash. Storing plain text passwords is never secure. Always use built-in hashing functions.
Code Example
<?php
$hash = password_hash("secret", PASSWORD_DEFAULT);
if (password_verify("secret", $hash)) {
echo "Password correct";
}
?>
Expected Output: Password correct
password_hash() generates a cryptographically secure hash with salt. password_verify() compares the password against the hash. The algorithm is chosen automatically based on what’s available.
10.5 Secure Sessions, HTTPS, CORS, Rate Limiting
Security measures for sessions, transport, cross-origin requests, and request rates.
Session security uses session.cookie_httponly to prevent JavaScript access and session.use_strict_mode for security. HTTPS encrypts all traffic. CORS controls cross-origin API access. Rate limiting prevents abuse.
Code Example
<?php
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
session_start();
session_regenerate_id(true);
?>
Expected Output: No direct output; session security enhanced
These settings make session cookies inaccessible to JavaScript and regenerate session IDs to prevent fixation attacks.
10.6 Secure File Handling
Secure file handling validates uploads to prevent malicious files.
File validation checks file type, size, and content. Allowed types should be restricted. File naming should use safe names. Upload directory should not be web-accessible.
Code Example
<?php
$allowed = ['image/jpeg', 'image/png'];
if (in_array($_FILES['file']['type'], $allowed) && $_FILES['file']['size'] < 2_000_000) {
move_uploaded_file($_FILES['file']['tmp_name'], "uploads/" . basename($_FILES['file']['name']));
echo "File uploaded";
} else {
echo "Invalid file";
}
?>
Expected Output: File uploaded if valid
The script checks MIME type and file size. Only allowed types and sizes are accepted. move_uploaded_file() validates the upload origin.
File Handling & Error Handling
11.1 Reading/Writing Files (fopen, fread, file_get_contents)
File handling allows reading from and writing to files on the server.
file_get_contents() reads an entire file into a string. file_put_contents() writes data to a file. fopen() provides streaming access for large files. Always handle file permissions and errors.
Code Example
<?php
// Write and read
file_put_contents("data.txt", "Hello World");
$data = file_get_contents("data.txt");
echo $data . "\n";
// Streaming write
$fp = fopen("log.txt", "a");
fwrite($fp, "New entry\n");
fclose($fp);
?>
Expected Output: Hello World
file_put_contents() writes the string to the file. file_get_contents() reads it back. fopen() with ‘a’ mode opens for appending, and fwrite() writes to the file.
11.2 CSV, JSON, XML Handling
PHP can process common data formats like CSV, JSON, and XML for data exchange.
JSON is lightweight and commonly used in APIs. CSV is used for tabular data. XML is used in legacy systems. PHP provides built-in functions for each format.
Code Example
<?php
// JSON
$json = json_encode(["name" => "Zaigham"]);
file_put_contents("data.json", $json);
$data = json_decode(file_get_contents("data.json"), true);
print_r($data);
?>
Expected Output: Array ( [name] => Zaigham )
json_encode() converts arrays to JSON strings. json_decode() converts JSON strings back to arrays with the true parameter.
11.3 Error Reporting & Custom Exceptions
Error reporting shows issues. Custom exceptions provide structured error handling.
Error reporting (error_reporting(E_ALL)) shows all errors. Exceptions provide structured error handling with try, catch, and throw. Custom exceptions extend the base Exception class.
Code Example
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class MyException extends Exception {}
try {
throw new MyException("Custom error");
} catch (MyException $e) {
echo $e->getMessage();
}
?>
Expected Output: Custom error
Error reporting displays all errors. The custom exception is thrown and caught. Exception objects provide methods like getMessage() for error details.
11.4 Logging & Xdebug
Logging records errors and events. Xdebug provides debugging and profiling.
Error logging uses error_log() to write to log files. Xdebug provides step-through debugging, stack traces, and performance profiling. Logs help diagnose issues in production.
Code Example
<?php
error_log("Error message", 3, "/var/log/php_errors.log");
?>
Expected Output: No output; logs to file
The error_log() function writes the message to the specified file. Xdebug provides enhanced debugging when installed and configured.
Composer & Package Management
12.1 Installing Composer
Composer is PHP’s dependency manager, essential for modern PHP development.
Composer installs and manages PHP packages. It resolves dependencies and provides autoloading. The installation is a one-time setup. Composer is used by all modern PHP frameworks.
Code Example
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"
Expected Output: Composer installed
The script downloads the Composer installer, runs it, and cleans up. Composer can be installed globally or per project.
12.2 composer.json & Dependency Management
composer.json defines project dependencies. Dependency management installs and updates packages.
composer.json lists required packages with version constraints. composer install installs all dependencies. composer update updates dependencies. Packages are stored in the vendor/ directory.
Code Example
{
"require": {
"monolog/monolog": "^3.0"
}
}
Expected Output: Dependencies installed
Composer reads composer.json, resolves dependencies, and downloads the required packages. Version constraints (^3.0) allow updates within the 3.x range.
12.3 Autoloading (PSR-4)
PSR-4 autoloading automatically loads classes when they’re used, eliminating manual includes.
PSR-4 maps namespaces to directory structures. Classes are loaded on demand. Composer generates an autoloader. composer dump-autoload regenerates the autoloader.
Code Example
{
"autoload": {
"psr-4": {"App\\": "src/"}
}
}
<?php
require 'vendor/autoload.php';
use App\Models\User;
$user = new User(); // Automatically loaded
?>
Expected Output: User class loaded successfully
The autoloader maps App\Models\User to src/Models/User.php. When the class is used, the autoloader includes the file automatically.
REST APIs & Web Services
13.1 REST Principles & CRUD API
REST (Representational State Transfer) is an architectural style for designing web APIs that use standard HTTP methods and principles to interact with resources. CRUD operations map to HTTP methods.
REST uses standard HTTP methods. GET retrieves resources. POST creates resources. PUT updates resources. DELETE removes resources. APIs return data in formats like JSON.
Code Example
<?php
$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;
switch ($method) {
case 'GET':
echo json_encode(["id" => $id, "title" => "Post $id"]);
break;
case 'POST':
$data = json_decode(file_get_contents('php://input'), true);
echo json_encode(["status" => "created", "data" => $data]);
break;
}
?>
Expected Output: {"id":"1","title":"Post 1"} for GET /post/1
The API handles different HTTP methods. GET returns resource data. POST creates new resources. The response is JSON encoded.
13.2 JSON Responses & HTTP Status Codes
JSON responses provide structured data. HTTP status codes indicate operation outcome.
JSON is the standard API response format. HTTP status codes communicate the result of a request. 2xx codes indicate success, 4xx codes indicate client-side errors, and 5xx codes indicate server-side errors.Always set the correct content type header.
Code Example
<?php
header('Content-Type: application/json');
http_response_code(200);
echo json_encode(["status" => "success", "data" => ["id" => 1]]);
?>
Expected Output: {"status":"success","data":{"id":1}}
header() sets the response content type. http_response_code() sets the HTTP status code. json_encode() converts the data to JSON format.
13.3 Consuming External APIs (cURL, Guzzle)
cURL and Guzzle are tools commonly used in PHP to send HTTP requests and communicate with external APIs.
cURL is PHP’s built-in HTTP client. Guzzle is a popular HTTP client library. Both handle requests, headers, and responses. They support GET, POST, PUT, DELETE.
Code Example
<?php
// cURL example
$ch = curl_init("https://jsonplaceholder.typicode.com/posts/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
print_r($data);
?>
Expected Output: Array from JSONPlaceholder API
curl_init() initializes the session. curl_setopt() sets options. curl_exec() executes the request and returns the response. curl_close() closes the session.
13.4 API Authentication (JWT, OAuth)
Authentication verifies API client identity. JWT and OAuth are common methods.
JWT (JSON Web Tokens) are self-contained tokens with user information. OAuth delegates authentication to providers like Google. JWTs are signed and can be verified on the server.
Code Example
<?php
// JWT example (conceptual)
use Firebase\JWT\JWT;
$payload = ['user_id' => 1, 'exp' => time() + 3600];
$jwt = JWT::encode($payload, 'secret', 'HS256');
// Client sends token in Authorization header
?>
Expected Output: Encoded JWT token
The JWT token encodes user data and expiration. It’s signed with a secret key. For authenticated requests, the client includes an access token in the Authorization HTTP header so the server can verify the requester’s identity or permissions.
13.5 API Security (CORS, Rate Limiting, Input Validation)
Security measures protect APIs from cross-origin attacks, abuse, and invalid data.
CORS (Cross-Origin Resource Sharing) controls which domains can access the API.Rate limiting controls how frequently a client can send requests to an API within a given period, helping prevent abuse and protect server resources. Input validation ensures data is valid before processing.
Code Example
<?php
// CORS headers
header("Access-Control-Allow-Origin: https://example.com");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
?>
Expected Output: Allows cross-origin requests
These headers tell browsers which origins, methods, and headers are allowed. This prevents unauthorized access while enabling legitimate cross-origin requests.
13.6 API Documentation (Swagger/OpenAPI)
Swagger/OpenAPI provides a standard way to document APIs with interactive documentation.
OpenAPI is a specification for API documentation. Swagger is a toolset that implements OpenAPI. Documentation describes endpoints, parameters, responses, and authentication.
Code Example
/**
* @OA\Get(
* path="/users",
* summary="List all users",
* @OA\Response(response=200, description="Successful operation")
* )
*/
Expected Output: Swagger UI renders documentation
Annotations are parsed to generate OpenAPI JSON. Swagger UI displays interactive documentation. This helps API consumers understand and test the API.
Modern PHP (8.x Features)
14.1 Union Types
Union types allow parameters and return values to accept multiple types.
Union types use the | syntax. They provide flexibility while maintaining type safety. Common uses include int|string, array|null. Union types are checked at runtime.
Code Example
<?php
function process(int|string $value): int|string {
return $value;
}
echo process(10) . "\n";
echo process("PHP");
?>
Expected Output:
10
PHP
The function accepts either integer or string. It returns the same type. This provides flexibility without sacrificing type safety.
14.2 Attributes (Annotations)
Attributes are structured metadata using #[...] syntax, replacing PHPDoc annotations.
Attributes attach metadata to classes, methods, properties, and functions. They’re strongly typed and can be read via reflection. Attributes enable features like routing, validation, and serialization.
Code Example
<?php
#[Route("/home")]
class HomeController {}
$reflection = new ReflectionClass(HomeController::class);
foreach ($reflection->getAttributes() as $attr) {
echo $attr->getName(); // Outputs: Route
}
?>
Expected Output: Route
The #[Route("/home")] attribute attaches metadata. Reflection reads the attribute. This enables framework features like automatic route registration.
14.3 Match Expression
Match is a stricter, more concise alternative to the switch statement.
Match is an expression that returns a value. It requires exact matches with no type coercion. Match must be exhaustive or have a default. It’s more concise and safer than switch.
Code Example
<?php
$status = 404;
$message = match($status) {
200 => "OK",
404 => "Not Found",
default => "Unknown"
};
echo $message; // Not Found
?>
Expected Output: Not Found
Match evaluates the expression and matches it to the cases. Each case returns a value. The default case handles unmatched values. Match is an expression, not a statement.
14.4 Nullsafe Operator
The nullsafe operator (?->) safely accesses properties and methods of potentially null objects.
The nullsafe operator short-circuits if the object is null. It avoids null check boilerplate. It’s useful for deep property access on objects that might be null.
Code Example
<?php
$user = null;
echo $user?->profile?->email ?? "Email not found";
?>
Expected Output: Email not found
If $user is null, the expression stops and returns null. The null coalescing operator (??) handles the null, providing a default value.
14.5 Constructor Property Promotion
Constructor property promotion reduces boilerplate by declaring properties in the constructor signature.
Properties are declared and initialized in the constructor parameters. This replaces separate property declarations and assignments. It makes classes more concise.
Code Example
<?php
class Post {
public function __construct(
public int $id,
public string $title
) {}
}
$post = new Post(1, "Hello");
echo $post->title; // Hello
?>
Expected Output: Hello
The public int $id in the constructor signature declares a property and initializes it with the constructor argument. This eliminates separate property declarations.
14.6 Named Arguments
Named arguments allow calling functions with arguments in any order by specifying parameter names.
Named arguments improve readability and reduce errors. They allow skipping default arguments. Named arguments are especially useful for functions with many parameters.
Code Example
<?php
function createPost($title, $content, $status = "draft") {
return "$title - $status";
}
echo createPost(content: "My content", title: "Hello");
?>
Expected Output: Hello - draft
Named arguments use the parameter name followed by a colon and the value. The order of arguments doesn’t matter. Default parameters can be skipped.
14.7 Throw Expression
Throw is now an expression, allowing exceptions to be thrown in expressions.
Throw expressions can be used in arrow functions, match expressions, and short circuit operations. This makes code more concise when throwing exceptions in expressions.
Code Example
<?php
$id = $_GET['id'] ?? throw new Exception("ID required");
echo $id;
?>
Expected Output: If no id in URL, throws exception; otherwise prints id
The throw expression is evaluated when the condition is met. It throws the exception immediately, stopping execution.
14.8 Just-In-Time (JIT) Compilation
JIT compiles PHP code to machine code at runtime, improving performance for CPU-intensive code.
JIT compiles frequently executed code to machine code, reducing execution time. It’s most effective for CPU-intensive operations. JIT is enabled in php.ini. Performance gains vary depending on the application.
Code Example
// No specific code example; conceptual
// Enable JIT in php.ini:
// opcache.jit = tracing
// opcache.jit_buffer_size = 64M
Expected Output: Performance improvement for CPU-intensive code
JIT analyzes running code and compiles hot paths to machine code. This eliminates interpreter overhead for frequently executed code.
Laravel Framework
15.1 MVC Architecture
MVC (Model-View-Controller) separates concerns in web applications.
Model handles data and business logic. View handles presentation. Controller handles requests and coordinates models and views. Laravel implements MVC with elegant syntax.
Code Example
// routes/web.php
Route::get('/users', [UserController::class, 'index']);
// app/Http/Controllers/UserController.php
class UserController {
public function index() {
$users = User::all();
return view('users.index', ['users' => $users]);
}
}
Expected Output: Renders the users view with data
The route maps to the controller method. The controller retrieves data from the model and returns a view with the data.
15.2 Routing & Controllers
Routing maps URLs to controllers. Controllers handle requests and return responses.
Routes define URL patterns. Controllers group related request handling logic. Routes can use closures or controller methods. Laravel provides RESTful resource routing.
Code Example
// web.php
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::get('/users/{id}', [UserController::class, 'show']);
Expected Output: Routes defined for CRUD operations
Routes map HTTP methods and URLs to controller methods. Parameters like {id} are passed to the controller method.
15.3 Middleware
Middleware filters HTTP requests entering the application.
Middleware runs before or after requests. Examples include authentication, logging, and CORS. Middleware can be applied globally to an entire application or assigned only to specific routes, depending on where its functionality is needed.
Code Example
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', function () {
return view('dashboard');
});
});
Expected Output: Authenticated access only
The auth middleware checks if the user is authenticated. If not, it redirects to the login page. If authenticated, the request continues to the route handler.
15.4 Eloquent ORM
Eloquent is Laravel’s ORM for database interaction with beautiful syntax.
Eloquent provides ActiveRecord implementation. Models represent database tables. Methods like where(), get(), first() build queries. Relationships are defined as methods.
Code Example
// Get users over 18
$users = User::where('age', '>', 18)->get();
// Relationship
class User extends Model {
public function posts() {
return $this->hasMany(Post::class);
}
}
// Access posts
$user = User::find(1);
$posts = $user->posts;
Expected Output: Collection of users or posts
Eloquent models provide fluent query builders. Relationships define how models connect. Query results are returned as collections.
15.5 Queues & Events
Queues defer slow tasks. Events trigger actions when things happen.
Queues process tasks asynchronously. Jobs are queued tasks. Events are actions that occur in the application. Listeners respond to events. This improves performance and enables event-driven architecture.
Code Example
# Create a job
php artisan make:job SendWelcomeEmail
# Dispatch the job
SendWelcomeEmail::dispatch($user);
# Process queue
php artisan queue:work
Expected Output: Job processed in background
Jobs are queued to databases, Redis, or other drivers. Workers process jobs asynchronously. This offloads slow operations from the web request lifecycle.
Testing
16.1 PHPUnit
PHPUnit is PHP’s testing framework for unit tests.
Unit tests verify individual components. Assertions check expected outcomes. Tests are organized in test classes extending TestCase. phpunit runs tests and reports results.
Code Example
<?php
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase {
public function testAdd() {
$this->assertEquals(5, add(2, 3));
}
}
?>
Expected Output: Test passes
The test method calls the function and asserts the expected result. PHPUnit executes the test and reports whether it passed or failed.
16.2 Feature Testing & Unit Testing
Feature tests verify complete features. Unit tests verify individual components.
Unit tests test isolated components. Feature tests test complete features with HTTP requests, database, and external services. Laravel provides tools for both.
Code Example
public function test_user_can_login() {
$response = $this->post('/login', [
'email' => 'test@example.com',
'password' => 'password'
]);
$response->assertStatus(302);
}
Expected Output: Assertion passes
The test simulates an HTTP request. It checks that the response status is correct. This verifies that the login feature works.
16.3 Mocking
Mocking replaces real objects with test doubles to isolate tests.
Mock objects simulate dependencies. They verify that methods are called correctly. Mocks can return specific values. This isolates the code being tested.
Code Example
$mock = $this->createMock(UserRepository::class);
$mock->method('find')->willReturn($user);
$service = new UserService($mock);
$result = $service->getUser(1);
Expected Output: Mock object returns stubbed value
The mock object is configured to return a specific value. The test code uses the mock instead of the real dependency. This isolates the test from external factors.
Performance Optimization
17.1 OPcache
OPcache stores compiled PHP code in memory, improving performance.
OPcache eliminates the compilation step for each request. It stores compiled opcode in shared memory. This significantly improves performance for repeated requests.
Code Example
; php.ini configuration
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
Expected Output: Faster PHP execution
OPcache caches compiled opcode. Subsequent requests use the cached version. This reduces CPU usage and speeds up response times.
17.2 Caching (Redis, Memcached)
Caching stores frequently accessed data in memory for faster retrieval.
Redis and Memcached are in-memory data stores. They store database results, sessions, and computed data. Caching reduces database load and speeds up responses.
Code Example
<?php
// Redis example
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('key', 'value');
echo $redis->get('key');
?>
Expected Output: value
Data is stored in memory with key-value pairs. Retrieval is much faster than database queries. Cached data can be expired to ensure freshness.
17.3 Database Optimization
Database optimization improves query performance and reduces load.
Indexes speed up lookups. Query optimization uses EXPLAIN to analyze queries. Caching reduces database load. **Avoid SELECT * ** to reduce data transfer.
Code Example
-- Create index
CREATE INDEX idx_user_email ON users(email);
-- Analyze query
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
Expected Output: Query execution plan
Indexes create fast lookups. EXPLAIN shows how the database executes the query. This helps identify optimization opportunities.
17.4 Queue Processing
Queues process tasks asynchronously, improving response times.
Queues offload slow operations to background workers. Examples include email sending, image processing, and report generation. This keeps web requests fast.
Code Example
# Laravel queue worker
php artisan queue:work
Expected Output: Processes queued jobs
The worker processes jobs from the queue. Jobs are executed asynchronously. This reduces the time the user waits for the response.
Deployment & Production Architecture
18.1 Apache & Nginx Setup
Apache and Nginx are web servers that serve PHP applications.
Apache uses mod_php or PHP-FPM. Nginx uses PHP-FPM. PHP-FPM communicates with the web server over FastCGI. Nginx is more efficient for static files.
Code Example
# Nginx configuration
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
Expected Output: PHP processed via FPM
Nginx passes PHP requests to PHP-FPM through a socket. PHP-FPM executes the script and returns the result. Nginx sends the response to the client.
18.2 PHP-FPM
PHP-FPM is the FastCGI Process Manager for PHP.
PHP-FPM manages worker processes for handling PHP requests. It can be configured for dynamic or static process pools. It provides process management and performance tuning.
Code Example
; php-fpm.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 2
pm.max_spare_servers = 8
Expected Output: Manages worker processes
PHP-FPM creates worker processes to handle requests. Dynamic mode adjusts the number of processes based on traffic. This provides efficient resource usage.
18.3 Docker
Docker containers isolate applications with their dependencies.
Docker packages applications with their dependencies. This ensures consistency across environments. Docker images are portable and reproducible.
Code Example
# Dockerfile
FROM php:8.3-fpm
COPY . /var/www/html
WORKDIR /var/www/html
RUN docker-php-ext-install pdo_mysql
Expected Output: Containerized PHP application
The Dockerfile defines the environment. The image includes PHP, extensions, and application code. The container runs the application consistently across different machines.
18.4 CI/CD (GitHub Actions)
CI/CD automates building, testing, and deploying applications.
CI (Continuous Integration) runs tests on code changes. CD (Continuous Delivery) automates deployment. GitHub Actions automates the CI/CD pipeline.
Code Example
# .github/workflows/deploy.yml
name: Deploy
on: push
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: composer install
- run: php artisan migrate
Expected Output: Automated deployment
The workflow runs on each push. It checks out code, installs dependencies, and runs migrations. This automates the deployment process.
18.5 Cloud Hosting
Cloud hosting platforms provide scalable infrastructure for PHP applications.
Platforms include AWS, DigitalOcean, Heroku, and Laravel Forge. They provide servers, databases, and scaling. Cloud hosting handles infrastructure management.
Code Example
# Deploy to AWS Elastic Beanstalk
eb deploy
# Deploy to Laravel Forge
# Forge automatically deploys on Git push
Expected Output: Application deployed to cloud
Cloud platforms manage servers, load balancing, and scaling. Developers can focus on writing and deploying code while the platform manages the underlying infrastructure and operational requirements.
Real-World Projects
19.1 Blog System
A blog system allows creating, editing, and publishing blog posts.
Features include post creation, categories, tags, comments, and user authentication. Laravel is commonly used. The system demonstrates CRUD operations and relationships.
Code Example
// routes/web.php
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{id}', [PostController::class, 'show']);
// PostController.php
class PostController {
public function index() {
$posts = Post::with('author')->latest()->get();
return view('posts.index', ['posts' => $posts]);
}
}
Expected Output: Blog posts listing and detail
The route maps to the controller. The controller retrieves posts with their authors. The view renders the posts.
19.2 E-Commerce Platform
An e-commerce platform sells products online with shopping cart and checkout.
Features include product catalog, shopping cart, checkout, payment processing, and order management. Laravel Cashier handles payments. Models include Product, Order, and User.
Code Example
// models
class Product extends Model {
protected $fillable = ['name', 'price', 'description'];
}
class Order extends Model {
public function user() {
return $this->belongsTo(User::class);
}
public function items() {
return $this->hasMany(OrderItem::class);
}
}
Expected Output: E-commerce functionality
Products are stored in the database. Users add items to their cart. Checkout processes payment and creates orders.
19.3 CRM Application
A CRM manages customer relationships, leads, and interactions.
Features include customer management, lead tracking, task management, and reporting. Models include Customer, Lead, Task, and User. Relationships connect customers to users.
Code Example
class Customer extends Model {
public function user() {
return $this->belongsTo(User::class);
}
public function tasks() {
return $this->hasMany(Task::class);
}
}
Expected Output: CRM functionality.
Users manage customers and tasks. Each customer belongs to a user. The system tracks interactions and follow-ups.
19.4 REST API Platform
A REST API platform provides endpoints for external applications to interact with data.
Features include authentication, CRUD operations, rate limiting, and documentation. Laravel API resources format responses. The API is consumed by frontend applications.
Code Example
// routes/api.php
Route::apiResource('products', ProductController::class);
// ProductController.php
class ProductController extends Controller {
public function index() {
return ProductResource::collection(Product::all());
}
}
Expected Output: Full CRUD API for products
The route defines API endpoints. The controller handles requests. Resources format responses for the API.
19.5 SaaS Application
A SaaS application provides software as a service with subscriptions.
Features include multi-tenancy, user management, subscriptions, billing, and permissions. Laravel Cashier handles subscriptions. Tenants are isolated.
Code Example
// models
class Tenant extends Model {
public function users() {
return $this->hasMany(User::class);
}
}
class Subscription extends Model {
public function tenant() {
return $this->belongsTo(Tenant::class);
}
}
Expected Output: SaaS application functionality
Each tenant has its own users and data. Subscriptions manage billing and access. Users are isolated to their tenant.
Career Readiness
20.1 Portfolio Development
A portfolio demonstrates your PHP development skills to employers.
Projects include blog system, e-commerce, REST API, and Laravel application. Documentation shows your thinking process. GitHub hosts your code. Projects should be complete and functional.
Code Example
# Portfolio Projects
1. Blog System - Full CRUD with authentication
2. E-commerce - Shopping cart with payment
3. REST API - Scalable API with documentation
4. Laravel App - Complete SaaS application
Expected Output: Professional portfolio
Build and host projects on GitHub. Write README files explaining each project. Include live demos when possible. Show code quality and organization.
20.2 Open Source Contributions
Contributing to open source PHP projects builds experience and visibility.
Projects include Laravel, WordPress, Composer packages, and PHP tools. Contributions include bug fixes, features, documentation, and testing. Start with small issues and work up.
Code Example
# Contribution workflow
git clone https://github.com/laravel/laravel
git checkout -b feature/fix-bug
# make changes
git commit -m "Fix bug"
git push origin feature/fix-bug
# Create pull request
Expected Output: Open source contribution
Fork the repository, create a feature branch, make changes, commit, push, and create a pull request. Reviewers will provide feedback before merging.
20.3 Technical Interviews
Technical interviews assess PHP knowledge and problem-solving skills.
Topics include OOP, PDO, security, MVC, Laravel, and problem-solving. Practice coding challenges and whiteboard interviews. Explain your reasoning clearly.
Code Example
// Common interview question
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
Expected Output: Demonstrates OOP knowledge
Interviews assess your understanding of concepts. Practice explaining code clearly. Demonstrate problem-solving approach.
20.4 System Design
System design demonstrates architectural thinking for PHP applications.
Topics include scalability, caching, queues, load balancing, and database design. Design high-level architecture. Consider performance, security, and maintainability.
Code Example
System Design: E-commerce API
1. Load Balancer (Nginx)
2. Application (PHP-FPM)
3. Cache (Redis)
4. Queue (Redis/SQS)
5. Database (MySQL)
6. Search (Elasticsearch)
Expected Output: System architecture design
Design a scalable system architecture. Consider components, data flow, and scalability. Explain trade-offs and decisions.
20.5 Professional Growth
Professional growth involves continuous learning and community engagement.
Stay updated with PHP 8.x features and modern frameworks. Follow PHP community news and blogs. Attend conferences and meetups. Contribute to open source. Network with other developers.
Code Example
# Professional Development Plan
1. Study PHP 8 features monthly
2. Follow Laravel News weekly
3. Contribute one open source PR per quarter
4. Attend one PHP conference yearly
5. Build one personal project per quarter
Expected Output: Professional growth plan
Continuously learn and grow. Stay engaged with the community. Build your network and skills. Document your learning and projects.