🚀 PHP Introduction
🎯 Complete Definition
PHP (Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. Created by Rasmus Lerdorf in 1994, PHP runs on the server side, generating dynamic web page content. It's the "P" in the LAMP stack (Linux, Apache, MySQL, PHP).
🔬 Core Characteristics
- Server-side: Code executes on the server, producing HTML sent to the client.
- Embedded in HTML: PHP tags
<?php ?>can be placed anywhere in HTML files. - Dynamic typing: Variables don't need type declarations (type inferred).
- Extensive ecosystem: Frameworks (Laravel, Symfony), CMS (WordPress, Drupal), e-commerce (Magento).
- Database integration: Native support for MySQL, PostgreSQL, MongoDB via extensions.
- Session management: Built-in sessions, cookies for user state.
- Cross-platform: Runs on Windows, Linux, macOS, most web servers.
📊 Industry Usage
PHP powers nearly 80% of websites whose server-side language we know, including Facebook (originally), Wikipedia, Slack, Etsy, and Mailchimp. WordPress alone powers over 40% of all websites. PHP 8.x brings JIT compilation, union types, attributes, and massive performance improvements.
📊 Basics & Syntax
🎯 Complete Definition
PHP syntax is similar to C and Perl. Scripts start with <?php and end with ?>. Statements end with semicolon. Whitespace is ignored. Comments: // single line, /* */ multi-line. PHP files can contain HTML, CSS, JavaScript alongside PHP.
🏗️ Basic Syntax Rules
- PHP tags:
<?php ... ?>(short tags<?= ?>for echo). - Echo / Print: Output data.
echocan take multiple parameters. - Case sensitivity: Variable names are case-sensitive; functions and keywords are not (but use consistent).
- Statements: Must end with
;. - Comments:
//,#,/* */.
📦 Variables & Data Types
🎯 Complete Definition
Variables in PHP start with $ and are dynamically typed. PHP supports 8 primitive types: booleans, integers, floats (doubles), strings, arrays, objects, resources, and NULL. Type juggling automatically converts types as needed, but strict typing is possible (declare(strict_types=1)).
🔤 Data Types
- string: Series of characters, e.g.
"hello",'world' - int: Whole numbers (32/64-bit, platform dependent)
- float: Decimal numbers (double precision)
- bool:
trueorfalse - array: Ordered maps (can be indexed or associative)
- object: Instances of classes
- NULL: No value
- resource: External resource (file handle, DB connection)
🔢 Operators
🎯 Complete Definition
Operators perform operations on variables and values. PHP has arithmetic, assignment, comparison, logical, bitwise, string, array, and type operators. Operator precedence determines evaluation order.
📋 Operator Categories
- Arithmetic:
+,-,*,/,%,**(exponentiation) - Assignment:
=,+=,-=,*=,/=,.=(string concat) - Comparison:
==,===(identical),!=,<>,!==,<,>,<=,>=,<=>(spaceship) - Logical:
and,or,xor,&&,||,! - String:
.(concatenation),.= - Array:
+(union),==,===,!=,<> - Type:
instanceof - Error Control:
@(suppress errors)
🔀 Control Flow
🎯 Complete Definition
Control structures determine execution path: if, else, elseif, switch, match (PHP 8). PHP also supports alternative syntax for templates (using : and endif; etc.).
🏗️ Control Structures
- if / elseif / else: Conditional branching.
- switch: Multi-way branch (loose comparison).
- match: PHP 8+ strict comparison, returns value.
- Alternative syntax:
if (cond): ... endif;useful in templates.
🔄 Loops
🎯 Complete Definition
Loops repeat code: while, do-while, for, foreach. break exits loop, continue skips iteration. foreach is ideal for arrays and objects.
🔄 Loop Types
- while: Check condition before each iteration.
- do-while: Executes at least once, then checks condition.
- for: Counter-based loop (init; condition; increment).
- foreach: Iterates over arrays/objects:
foreach ($array as $key => $value).
📋 Arrays
🎯 Complete Definition
Arrays are ordered maps (key-value pairs). They can be indexed (0,1,2...) or associative (string keys). PHP arrays are flexible, acting like lists, hash tables, dictionaries, stacks, queues. Array functions provide powerful manipulation.
📊 Array Operations
- Indexed:
$arr = [1,2,3];orarray(1,2,3); - Associative:
$user = ['name' => 'John', 'age' => 30]; - Multidimensional: Arrays within arrays.
- Common functions:
count(),array_push(),array_pop(),array_merge(),array_keys(),in_array(),sort().
⚙️ Functions
🎯 Complete Definition
Functions encapsulate reusable code. Defined with function name($param) { }. PHP supports type declarations, default values, variadic arguments (...), return type declarations, and strict typing. Functions can be anonymous (closures) and can use variable scope (global, static).
⚙️ Function Features
- Parameter types:
function add(int $a, int $b): int {} - Default values:
function greet($name = "Guest") - Variadic:
function sum(...$numbers) - Return type:
: ?string(nullable),: void - Strict typing:
declare(strict_types=1); - Anonymous functions:
$func = function($x) { return $x*2; }; - Arrow functions (PHP 7.4+):
fn($x) => $x*2
📝 Strings
🎯 Complete Definition
Strings can be specified in four ways: single quoted, double quoted, heredoc, nowdoc. Double quotes and heredoc interpret variables and escape sequences. Single quotes are literal. PHP has extensive string functions: strlen(), strpos(), substr(), str_replace(), trim(), explode()/implode().
🔤 String Operations
- Concatenation:
$a . $b - Length:
strlen($str)(bytes, not characters for multibyte; usemb_strlenfor UTF-8) - Search:
strpos($haystack, $needle) - Replace:
str_replace($search, $replace, $subject) - Substring:
substr($str, $start, $length) - Split/Join:
explode($delimiter, $str),implode($glue, $array) - Formatting:
printf(),sprintf()
📨 Forms & Superglobals
🎯 Complete Definition
PHP superglobals are built-in variables that are always accessible. For form handling: $_GET (URL parameters), $_POST (form data), $_REQUEST (both). Other superglobals: $_SERVER, $_SESSION, $_COOKIE, $_FILES (uploads), $_ENV. Always sanitize and validate user input!
📨 Common Superglobals
- $_GET: Associative array of URL query parameters.
- $_POST: Data from HTTP POST method (forms).
- $_REQUEST: Combined GET/POST/COOKIE (use with caution).
- $_SERVER: Server and execution environment info.
- $_FILES: Uploaded files.
- $_SESSION / $_COOKIE: Session and cookie data.
💾 File Handling
🎯 Complete Definition
File functions allow reading/writing files on the server. Common functions: fopen(), fread(), fwrite(), fclose(), file_get_contents(), file_put_contents(), fgets(), feof(). Check permissions and handle errors.
📁 File Modes
r– read only, pointer at beginning.w– write only, truncates, creates if not exists.a– append, creates if not exists.r+– read/write, pointer at beginning.w+– read/write, truncates.a+– read/append.xb– exclusive create, binary.
"; } fclose($handle); } // Write with fopen $fp = fopen("newfile.txt", "w"); fwrite($fp, "First line\n"); fwrite($fp, "Second line"); fclose($fp); // Check existence if (file_exists("data.txt")) { echo "Filesize: " . filesize("data.txt"); } ?>
🔐 Sessions & Cookies
🎯 Complete Definition
Sessions store user-specific data across pages (server-side). Start with session_start(), then read/write $_SESSION array. Cookies store small data on client side; set with setcookie(), read from $_COOKIE. Sessions are more secure for sensitive data.
🔐 Session & Cookie Functions
session_start()– start or resume session.$_SESSION['key'] = value;– store data.session_destroy()– destroy session.setcookie(name, value, expire, path, domain, secure, httponly)isset($_COOKIE['name'])– check cookie.unset($_COOKIE['name'])– remove cookie (by setting past expiry).
🗄️ MySQL & PDO
🎯 Complete Definition
PDO (PHP Data Objects) is a consistent interface for accessing databases. It supports MySQL, PostgreSQL, SQLite, etc. Prepared statements prevent SQL injection. Use new PDO(), then query with prepare(), execute(), fetch().
🗄️ PDO Operations
- Connect:
$pdo = new PDO($dsn, $user, $pass); - Prepared statement (SELECT):
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?"); - Execute:
$stmt->execute([$id]); - Fetch:
$row = $stmt->fetch();(assoc array by default) - Insert/Update/Delete: similar with execute.
- Error handling: set error mode to exception:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
🏗️ OOP & Advanced
🎯 Complete Definition
Object-Oriented PHP supports classes, inheritance, interfaces, traits, abstract classes, and more. Visibility: public, protected, private. Magic methods (__construct(), __destruct(), __get(), __set(), __call(), etc.) enable powerful behaviors. Namespaces organize code. Modern PHP (8+) adds union types, attributes, named arguments, constructor property promotion, and match expressions.
🚀 Advanced Features
- Constructor property promotion:
public function __construct(private string $name) {} - Union types:
int|string $value - Named arguments:
func(age: 30, name: 'John') - Attributes:
#[Route('/api')] - Traits: Reusable code blocks.
- Anonymous classes:
$obj = new class { ... }; - Generators:
yieldfor memory-efficient iteration.