3807 words
19 minutes
PHP Complete Guide - Server-Side Programming
🐘 PHP Complete Guide - Server-Side Programming
![]()
📚 Table of Contents
- What is PHP?
- Basic Syntax
- Variables
- Data Types
- Operators
- Strings
- Arrays
- Conditionals
- Loops
- Functions
- Superglobals
- Forms Handling
- File Handling
- Sessions and Cookies
- MySQL Database
- PDO (Secure Database)
- Object-Oriented PHP
- Error Handling
- Security Best Practices
- Practical Projects
1. What is PHP?
PHP = PHP Hypertext Preprocessor
PHP is a server-side scripting language for web development.
What can PHP do?
- ✅ Generate dynamic web pages
- ✅ Handle forms
- ✅ Access databases
- ✅ Create sessions/cookies
- ✅ Send emails
- ✅ File manipulation
How PHP Works
Browser → Request → Server (PHP) → DatabaseBrowser ← Response ← Server (PHP) ← Database2. Basic Syntax
PHP Tags
<?php // PHP code here echo "Hello, World!";?>
<!-- Short echo tag --><?= "Hello" ?>
<!-- HTML with PHP --><!DOCTYPE html><html><body> <h1><?php echo "Hello, World!"; ?></h1> <p><?= "This is PHP" ?></p></body></html>Comments
<?php// Single line comment
# Another single line comment
/* Multi-line comment*/
/** * Documentation comment * @param string $name * @return string */?>Output
<?php// echo - can output multiple valuesecho "Hello", " ", "World";
// print - returns 1, single valueprint "Hello World";
// print_r - for arrays (human-readable)print_r($array);
// var_dump - detailed info (debugging)var_dump($variable);
// var_export - valid PHP code outputvar_export($array);?>3. Variables
Creating Variables
<?php// Variables start with $$name = "Ahmed";$age = 25;$price = 19.99;$isActive = true;
// Case-sensitive$color = "red";$Color = "blue"; // Different variable!
// Variable variables$varName = "message";$$varName = "Hello"; // Creates $messageecho $message; // "Hello"?>Variable Scope
<?php$globalVar = "I'm global";
function test() { // Cannot access $globalVar directly
// Use global keyword global $globalVar; echo $globalVar;
// Or use $GLOBALS echo $GLOBALS['globalVar'];
// Local variable $localVar = "I'm local";}
// Static variable (keeps value between calls)function counter() { static $count = 0; $count++; return $count;}
echo counter(); // 1echo counter(); // 2echo counter(); // 3?>Constants
<?php// Using define()define("SITE_NAME", "My Website");define("MAX_USERS", 100);
// Using const (PHP 5.3+)const PI = 3.14159;const GREETING = "Hello";
// Case-insensitive (deprecated in PHP 7.3)define("HELLO", "World", true);
// Using constantecho SITE_NAME;echo constant("SITE_NAME");
// Check if definedif (defined("SITE_NAME")) { echo SITE_NAME;}
// Magic constantsecho __FILE__; // Full path to fileecho __DIR__; // Directory of fileecho __LINE__; // Current line numberecho __FUNCTION__; // Function nameecho __CLASS__; // Class nameecho __METHOD__; // Class method name?>4. Data Types
Types
<?php// String$str = "Hello World";
// Integer$int = 42;$negative = -17;$hex = 0x1A; // 26$octal = 0755; // 493$binary = 0b11; // 3
// Float$float = 3.14;$scientific = 2.5e3; // 2500
// Boolean$bool = true;$bool2 = false;
// Array$arr = array(1, 2, 3);$arr2 = [1, 2, 3];
// Objectclass Person {}$obj = new Person();
// NULL$null = null;
// Resource (file handle, database connection)$file = fopen("file.txt", "r");?>Type Checking
<?php$var = "Hello";
// Get typeecho gettype($var); // "string"
// Check specific typeis_string($var); // trueis_int($var); // falseis_float($var); // falseis_bool($var); // falseis_array($var); // falseis_object($var); // falseis_null($var); // falseis_numeric($var); // falseis_callable($var); // false
// isset vs empty$a = "";$b = null;$c = 0;
isset($a); // true (exists)isset($b); // false (null)isset($d); // false (not defined)
empty($a); // true (empty string)empty($b); // true (null)empty($c); // true (0 is considered empty)?>Type Casting
<?php$str = "42";
// Cast to int$int = (int) $str; // 42$int = (integer) $str; // 42$int = intval($str); // 42
// Cast to float$float = (float) $str; // 42.0$float = floatval($str); // 42.0
// Cast to string$string = (string) 42; // "42"$string = strval(42); // "42"
// Cast to bool$bool = (bool) "hello"; // true$bool = (bool) ""; // false$bool = (bool) 0; // false
// Cast to array$arr = (array) "hello"; // ["hello"]
// Cast to object$obj = (object) ["a" => 1]; // stdClass?>5. Operators
Arithmetic Operators
<?php$a = 10;$b = 3;
echo $a + $b; // 13 (addition)echo $a - $b; // 7 (subtraction)echo $a * $b; // 30 (multiplication)echo $a / $b; // 3.333... (division)echo $a % $b; // 1 (modulus)echo $a ** $b; // 1000 (power)
// Increment/Decrement$x = 5;$x++; // 6$x--; // 5++$x; // 6 (pre-increment)?>Comparison Operators
<?php$a = 5;$b = "5";
// Loose comparison (type juggling)var_dump($a == $b); // truevar_dump($a != $b); // false
// Strict comparison (type must match)var_dump($a === $b); // falsevar_dump($a !== $b); // true
// Other comparisonsvar_dump($a > 3); // truevar_dump($a < 3); // falsevar_dump($a >= 5); // truevar_dump($a <= 5); // true
// Spaceship operator (PHP 7)echo 1 <=> 2; // -1 (1 < 2)echo 2 <=> 2; // 0 (2 == 2)echo 3 <=> 2; // 1 (3 > 2)?>Logical Operators
<?php$a = true;$b = false;
var_dump($a && $b); // false (AND)var_dump($a and $b); // false (AND, lower precedence)
var_dump($a || $b); // true (OR)var_dump($a or $b); // true (OR, lower precedence)
var_dump(!$a); // false (NOT)
var_dump($a xor $b); // true (XOR - one or other, not both)?>String Operators
<?php$a = "Hello";$b = "World";
// Concatenationecho $a . " " . $b; // "Hello World"
// Concatenation assignment$a .= " World"; // "Hello World"?>Null Coalescing Operator (PHP 7)
<?php// Returns first non-null value$name = $_GET['name'] ?? 'Guest';
// Chaining$name = $_GET['name'] ?? $_POST['name'] ?? 'Guest';
// Null coalescing assignment (PHP 7.4)$name ??= 'Guest';?>6. Strings
Creating Strings
<?php// Single quotes (literal)$str1 = 'Hello World';$str2 = 'It\'s a test'; // Escape quote
// Double quotes (interprets variables)$name = "Ahmed";$str3 = "Hello $name"; // "Hello Ahmed"$str4 = "Hello {$name}!"; // "Hello Ahmed!"$str5 = "Hello ${name}"; // "Hello Ahmed"
// Heredoc (like double quotes)$html = <<<HTML<div> <h1>Hello $name</h1></div>HTML;
// Nowdoc (like single quotes, PHP 5.3+)$text = <<<'TEXT'This is literal text.Variables like $name are not parsed.TEXT;?>String Functions
<?php$str = "Hello, World!";
// Lengthecho strlen($str); // 13
// Find positionecho strpos($str, "World"); // 7echo strrpos($str, "o"); // 8 (last occurrence)
// Extractecho substr($str, 0, 5); // "Hello"echo substr($str, -6); // "World!"
// Replaceecho str_replace("World", "PHP", $str); // "Hello, PHP!"
// Caseecho strtoupper($str); // "HELLO, WORLD!"echo strtolower($str); // "hello, world!"echo ucfirst("hello"); // "Hello"echo ucwords("hello world"); // "Hello World"
// Trimecho trim(" hello "); // "hello"echo ltrim(" hello "); // "hello "echo rtrim(" hello "); // " hello"
// Split and join$arr = explode(",", "a,b,c"); // ["a", "b", "c"]$str = implode("-", $arr); // "a-b-c"
// Reverseecho strrev("hello"); // "olleh"
// Repeatecho str_repeat("ha", 3); // "hahaha"
// Paddingecho str_pad("5", 3, "0", STR_PAD_LEFT); // "005"
// Compareecho strcmp("a", "b"); // -1 (case-sensitive)echo strcasecmp("A", "a"); // 0 (case-insensitive)
// Check contentvar_dump(str_contains("Hello World", "World")); // true (PHP 8)var_dump(str_starts_with("Hello", "He")); // true (PHP 8)var_dump(str_ends_with("Hello", "lo")); // true (PHP 8)?>7. Arrays
Creating Arrays
<?php// Indexed array$fruits = array("Apple", "Banana", "Orange");$fruits = ["Apple", "Banana", "Orange"];
// Associative array$user = array( "name" => "Ahmed", "age" => 25, "city" => "Casablanca");
$user = [ "name" => "Ahmed", "age" => 25, "city" => "Casablanca"];
// Multi-dimensional array$users = [ ["name" => "Ahmed", "age" => 25], ["name" => "Sara", "age" => 22], ["name" => "Ali", "age" => 30]];?>Accessing Elements
<?php$fruits = ["Apple", "Banana", "Orange"];$user = ["name" => "Ahmed", "age" => 25];
echo $fruits[0]; // "Apple"echo $fruits[1]; // "Banana"
echo $user["name"]; // "Ahmed"echo $user["age"]; // 25
// Check if key existsif (isset($user["email"])) { echo $user["email"];}
// Null coalescingecho $user["email"] ?? "No email";?>Modifying Arrays
<?php$arr = [1, 2, 3];
// Add element$arr[] = 4; // [1, 2, 3, 4]array_push($arr, 5, 6); // [1, 2, 3, 4, 5, 6]array_unshift($arr, 0); // [0, 1, 2, 3, 4, 5, 6]
// Remove elementarray_pop($arr); // Remove lastarray_shift($arr); // Remove firstunset($arr[2]); // Remove specific index
// Merge arrays$merged = array_merge([1, 2], [3, 4]); // [1, 2, 3, 4]
// Spread operator (PHP 7.4)$merged = [...[1, 2], ...[3, 4]];?>Array Functions
<?php$arr = [3, 1, 4, 1, 5, 9, 2, 6];
// Countecho count($arr); // 8echo sizeof($arr); // 8
// Searchecho in_array(5, $arr); // trueecho array_search(5, $arr); // 4 (index)echo array_key_exists("name", $user); // true
// Sortsort($arr); // Sort ascendingrsort($arr); // Sort descendingasort($arr); // Sort, maintain keysksort($arr); // Sort by keys
// Filter$evens = array_filter($arr, fn($n) => $n % 2 === 0);
// Map$doubled = array_map(fn($n) => $n * 2, $arr);
// Reduce$sum = array_reduce($arr, fn($acc, $n) => $acc + $n, 0);
// Keys and values$keys = array_keys($user); // ["name", "age"]$values = array_values($user); // ["Ahmed", 25]
// Flip$flipped = array_flip(["a" => 1, "b" => 2]); // [1 => "a", 2 => "b"]
// Unique$unique = array_unique([1, 2, 2, 3, 3, 3]); // [1, 2, 3]
// Slice$slice = array_slice($arr, 0, 3); // First 3 elements
// Combine$combined = array_combine(["a", "b"], [1, 2]); // ["a" => 1, "b" => 2]
// Column (from 2D array)$names = array_column($users, "name"); // ["Ahmed", "Sara", "Ali"]?>Looping Arrays
<?php$fruits = ["Apple", "Banana", "Orange"];
// foreachforeach ($fruits as $fruit) { echo $fruit;}
// With indexforeach ($fruits as $index => $fruit) { echo "$index: $fruit";}
// Associative$user = ["name" => "Ahmed", "age" => 25];foreach ($user as $key => $value) { echo "$key: $value";}
// for loopfor ($i = 0; $i < count($fruits); $i++) { echo $fruits[$i];}?>8. Conditionals
if / else if / else
<?php$age = 18;
if ($age < 13) { echo "Child";} elseif ($age < 20) { echo "Teenager";} else { echo "Adult";}
// Alternative syntax (for templates)if ($age >= 18): echo "Adult";else: echo "Minor";endif;?>Ternary Operator
<?php$age = 20;$status = ($age >= 18) ? "Adult" : "Minor";
// Short ternary (Elvis operator)$name = $_GET['name'] ?: "Guest"; // Use "Guest" if falsy?>Switch
<?php$day = 3;
switch ($day) { case 1: echo "Monday"; break; case 2: echo "Tuesday"; break; case 3: echo "Wednesday"; break; default: echo "Unknown";}
// Match expression (PHP 8)$result = match($day) { 1 => "Monday", 2 => "Tuesday", 3 => "Wednesday", default => "Unknown"};?>9. Loops
for Loop
<?phpfor ($i = 0; $i < 5; $i++) { echo $i; // 0, 1, 2, 3, 4}?>while Loop
<?php$i = 0;while ($i < 5) { echo $i; $i++;}?>do…while Loop
<?php$i = 0;do { echo $i; $i++;} while ($i < 5);?>foreach Loop
<?php$arr = ["a", "b", "c"];
foreach ($arr as $item) { echo $item;}
foreach ($arr as $index => $item) { echo "$index: $item";}
// Modify by referenceforeach ($arr as &$item) { $item = strtoupper($item);}unset($item); // Important: unset reference?>break and continue
<?phpfor ($i = 0; $i < 10; $i++) { if ($i === 5) break; // Exit loop if ($i === 2) continue; // Skip iteration echo $i;}// Output: 0, 1, 3, 4?>10. Functions
Basic Functions
<?php// Define functionfunction greet($name) { return "Hello, $name!";}
// Call functionecho greet("Ahmed"); // "Hello, Ahmed!"
// Default parametersfunction greet2($name = "Guest") { return "Hello, $name!";}
echo greet2(); // "Hello, Guest!"echo greet2("Ahmed"); // "Hello, Ahmed!"?>Type Declarations (PHP 7+)
<?php// Parameter typesfunction add(int $a, int $b): int { return $a + $b;}
// Return typefunction getName(): string { return "Ahmed";}
// Nullable typefunction findUser(?int $id): ?array { return null;}
// Union types (PHP 8)function process(int|string $value): int|string { return $value;}
// Mixed type (PHP 8)function anything(mixed $value): mixed { return $value;}?>Variable Arguments
<?php// Variadic functionfunction sum(...$numbers) { return array_sum($numbers);}
echo sum(1, 2, 3); // 6echo sum(1, 2, 3, 4); // 10
// Spread operator$nums = [1, 2, 3];echo sum(...$nums); // 6?>Anonymous Functions (Closures)
<?php// Anonymous function$greet = function($name) { return "Hello, $name!";};
echo $greet("Ahmed");
// Arrow function (PHP 7.4)$double = fn($n) => $n * 2;echo $double(5); // 10
// Closure with use$multiplier = 3;$multiply = function($n) use ($multiplier) { return $n * $multiplier;};echo $multiply(5); // 15?>11. Superglobals
$_GET
<?php// URL: page.php?name=Ahmed&age=25
$name = $_GET['name']; // "Ahmed"$age = $_GET['age']; // "25"
// Safe access$name = $_GET['name'] ?? 'Guest';?>$_POST
<?php// Form with method="POST"if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = $_POST['name']; $email = $_POST['email'];}?>$_REQUEST
<?php// Contains $_GET, $_POST, and $_COOKIE$name = $_REQUEST['name'];?>$_SERVER
<?phpecho $_SERVER['REQUEST_METHOD']; // GET, POSTecho $_SERVER['HTTP_HOST']; // Domain nameecho $_SERVER['REQUEST_URI']; // /page.php?id=1echo $_SERVER['REMOTE_ADDR']; // Client IPecho $_SERVER['HTTP_USER_AGENT']; // Browser infoecho $_SERVER['DOCUMENT_ROOT']; // Server pathecho $_SERVER['PHP_SELF']; // Current script?>$_SESSION
<?phpsession_start();
// Set session$_SESSION['user_id'] = 123;$_SESSION['username'] = 'Ahmed';
// Get session$userId = $_SESSION['user_id'];
// Check if setif (isset($_SESSION['user_id'])) { echo "Logged in!";}
// Destroy sessionsession_destroy();?>$_COOKIE
<?php// Set cookie (before any output!)setcookie("username", "Ahmed", time() + 86400); // 1 day
// Get cookie$username = $_COOKIE['username'] ?? 'Guest';
// Delete cookiesetcookie("username", "", time() - 3600);?>$_FILES
<?php// Handle file uploadif ($_FILES['upload']['error'] === UPLOAD_ERR_OK) { $name = $_FILES['upload']['name']; $tmp = $_FILES['upload']['tmp_name']; $size = $_FILES['upload']['size']; $type = $_FILES['upload']['type'];
move_uploaded_file($tmp, "uploads/$name");}?>12. Forms Handling
HTML Form
<form action="process.php" method="POST" enctype="multipart/form-data"> <input type="text" name="username" required> <input type="email" name="email" required> <input type="password" name="password" required> <input type="file" name="avatar"> <button type="submit">Submit</button></form>Processing Form
<?phpif ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Sanitize input $username = htmlspecialchars(trim($_POST['username'])); $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $password = $_POST['password'];
// Validate $errors = [];
if (empty($username)) { $errors[] = "Username is required"; }
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email"; }
if (strlen($password) < 8) { $errors[] = "Password must be at least 8 characters"; }
// Handle file upload if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === 0) { $allowed = ['jpg', 'jpeg', 'png', 'gif']; $ext = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
if (in_array(strtolower($ext), $allowed)) { $newName = uniqid() . '.' . $ext; move_uploaded_file($_FILES['avatar']['tmp_name'], "uploads/$newName"); } else { $errors[] = "Invalid file type"; } }
if (empty($errors)) { // Process data... header("Location: success.php"); exit; }}?>13. File Handling
Read Files
<?php// Read entire file$content = file_get_contents("file.txt");
// Read into array (line by line)$lines = file("file.txt", FILE_IGNORE_NEW_LINES);
// Read with handle$file = fopen("file.txt", "r");while (!feof($file)) { $line = fgets($file); echo $line;}fclose($file);
// Read character by character$file = fopen("file.txt", "r");while (!feof($file)) { echo fgetc($file);}fclose($file);?>Write Files
<?php// Write (overwrite)file_put_contents("file.txt", "Hello World");
// Appendfile_put_contents("file.txt", "New line\n", FILE_APPEND);
// Write with handle$file = fopen("file.txt", "w"); // w = write, a = appendfwrite($file, "Hello World");fclose($file);?>File Operations
<?php// Check if existsif (file_exists("file.txt")) { echo "File exists!";}
// Check if readable/writableis_readable("file.txt");is_writable("file.txt");
// Get file infoecho filesize("file.txt"); // Size in bytesecho filemtime("file.txt"); // Last modified timeecho pathinfo("file.txt", PATHINFO_EXTENSION); // Extension
// Copy, rename, deletecopy("file.txt", "backup.txt");rename("file.txt", "newname.txt");unlink("file.txt"); // Delete
// Directory operationsmkdir("new_folder");rmdir("empty_folder");$files = scandir("folder"); // List files?>14. Sessions and Cookies
Sessions
<?php// Start session (must be first!)session_start();
// Set session data$_SESSION['user_id'] = 123;$_SESSION['username'] = 'Ahmed';$_SESSION['logged_in'] = true;
// Get session dataif (isset($_SESSION['logged_in']) && $_SESSION['logged_in']) { echo "Welcome, " . $_SESSION['username'];}
// Unset specific sessionunset($_SESSION['username']);
// Destroy all session datasession_destroy();
// Regenerate session ID (security)session_regenerate_id(true);?>Cookies
<?php// Set cookie// setcookie(name, value, expire, path, domain, secure, httponly)setcookie("user", "Ahmed", time() + 3600); // 1 hoursetcookie("theme", "dark", time() + 86400 * 30, "/"); // 30 days
// HTTP only (not accessible by JavaScript)setcookie("session", "abc123", time() + 3600, "/", "", true, true);
// Get cookie$user = $_COOKIE['user'] ?? 'Guest';
// Delete cookiesetcookie("user", "", time() - 3600);
// Check if cookie existsif (isset($_COOKIE['user'])) { echo "Cookie exists";}?>15. MySQL Database
Connect (mysqli)
<?php// Procedural$conn = mysqli_connect("localhost", "username", "password", "database");
if (!$conn) { die("Connection failed: " . mysqli_connect_error());}
// Object-oriented$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}?>CRUD Operations
<?php// CREATE$sql = "INSERT INTO users (name, email) VALUES ('Ahmed', 'ahmed@mail.com')";mysqli_query($conn, $sql);
// READ$sql = "SELECT * FROM users";$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) { echo $row['name'] . " - " . $row['email'];}
// UPDATE$sql = "UPDATE users SET name = 'Sara' WHERE id = 1";mysqli_query($conn, $sql);
// DELETE$sql = "DELETE FROM users WHERE id = 1";mysqli_query($conn, $sql);
// Close connectionmysqli_close($conn);?>Prepared Statements (SAFE!)
<?php// Prepare$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
// Bind parameters$stmt->bind_param("s", $email); // s = string, i = int, d = double
// Execute$email = "ahmed@mail.com";$stmt->execute();
// Get result$result = $stmt->get_result();while ($row = $result->fetch_assoc()) { echo $row['name'];}
$stmt->close();?>16. PDO (Secure Database)
Connect
<?phptry { $pdo = new PDO( "mysql:host=localhost;dbname=mydb;charset=utf8mb4", "username", "password", [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false ] );} catch (PDOException $e) { die("Connection failed: " . $e->getMessage());}?>CRUD with PDO
<?php// CREATE$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");$stmt->execute([$name, $email]);$lastId = $pdo->lastInsertId();
// READ$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");$stmt->execute([$id]);$user = $stmt->fetch();
// READ all$stmt = $pdo->query("SELECT * FROM users");$users = $stmt->fetchAll();
// UPDATE$stmt = $pdo->prepare("UPDATE users SET name = ? WHERE id = ?");$stmt->execute([$name, $id]);
// DELETE$stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");$stmt->execute([$id]);?>Named Parameters
<?php$stmt = $pdo->prepare("SELECT * FROM users WHERE name = :name AND age > :age");$stmt->execute([ ':name' => $name, ':age' => $age]);$users = $stmt->fetchAll();?>17. Object-Oriented PHP
Basic Class
<?phpclass User { // Properties public $name; public $email; private $password; protected $role;
// Constructor public function __construct($name, $email) { $this->name = $name; $this->email = $email; }
// Method public function greet() { return "Hello, " . $this->name; }
// Getter public function getEmail() { return $this->email; }
// Setter public function setPassword($password) { $this->password = password_hash($password, PASSWORD_DEFAULT); }
// Static method public static function create($name, $email) { return new self($name, $email); }
// Destructor public function __destruct() { echo "User destroyed"; }}
// Create object$user = new User("Ahmed", "ahmed@mail.com");echo $user->greet();echo $user->name;
// Static method$user2 = User::create("Sara", "sara@mail.com");?>Inheritance
<?phpclass Animal { protected $name;
public function __construct($name) { $this->name = $name; }
public function speak() { return "Some sound"; }}
class Dog extends Animal { public function speak() { return "{$this->name} says: Woof!"; }}
class Cat extends Animal { public function speak() { return "{$this->name} says: Meow!"; }}
$dog = new Dog("Buddy");echo $dog->speak(); // "Buddy says: Woof!"?>Interface and Abstract
<?php// Interfaceinterface Drawable { public function draw();}
// Abstract classabstract class Shape { abstract public function area();
public function describe() { return "This is a shape"; }}
class Circle extends Shape implements Drawable { private $radius;
public function __construct($radius) { $this->radius = $radius; }
public function area() { return pi() * $this->radius ** 2; }
public function draw() { return "Drawing circle"; }}?>Traits
<?phptrait Loggable { public function log($message) { echo "[LOG] $message"; }}
trait Timestampable { public function touch() { return date('Y-m-d H:i:s'); }}
class User { use Loggable, Timestampable;
public function save() { $this->log("User saved"); }}
$user = new User();$user->log("Hello");echo $user->touch();?>18. Error Handling
try / catch
<?phptry { $result = 10 / 0;} catch (DivisionByZeroError $e) { echo "Cannot divide by zero!";} catch (Exception $e) { echo "Error: " . $e->getMessage();} finally { echo "This always runs";}?>Custom Exceptions
<?phpclass ValidationException extends Exception { protected $errors = [];
public function __construct($errors) { parent::__construct("Validation failed"); $this->errors = $errors; }
public function getErrors() { return $this->errors; }}
function validate($data) { $errors = []; if (empty($data['name'])) { $errors[] = "Name is required"; } if (!empty($errors)) { throw new ValidationException($errors); }}
try { validate([]);} catch (ValidationException $e) { print_r($e->getErrors());}?>Error Handling
<?php// Set error handlerset_error_handler(function($errno, $errstr, $errfile, $errline) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline);});
// Set exception handlerset_exception_handler(function($e) { echo "Uncaught exception: " . $e->getMessage();});
// Error reportingerror_reporting(E_ALL); // All errorsini_set('display_errors', 0); // Don't show to usersini_set('log_errors', 1); // Log errors?>19. Security Best Practices
SQL Injection Prevention
<?php// BAD - Never do this!$sql = "SELECT * FROM users WHERE id = " . $_GET['id'];
// GOOD - Use prepared statements$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");$stmt->execute([$_GET['id']]);?>XSS Prevention
<?php// BADecho $_GET['name'];
// GOODecho htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
// Even better - use a functionfunction escape($value) { return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');}?>CSRF Protection
<?php// Generate tokensession_start();$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// In formecho '<input type="hidden" name="csrf_token" value="' . $_SESSION['csrf_token'] . '">';
// Validateif ($_POST['csrf_token'] !== $_SESSION['csrf_token']) { die("CSRF token mismatch!");}?>Password Hashing
<?php// Hash password$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// Verify passwordif (password_verify($inputPassword, $hashedPassword)) { echo "Password is correct!";}
// Check if rehash neededif (password_needs_rehash($hashedPassword, PASSWORD_DEFAULT)) { $hashedPassword = password_hash($password, PASSWORD_DEFAULT); // Update in database}?>Input Validation
<?php// Filter and validate$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);
// Sanitize$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);$url = filter_input(INPUT_POST, 'url', FILTER_SANITIZE_URL);
// Custom validationfunction validateUsername($username) { return preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username);}?>20. Practical Projects
Simple Login System
<?phpsession_start();
$pdo = new PDO("mysql:host=localhost;dbname=myapp", "user", "pass", [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
function escape($str) { return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');}
// login.phpif ($_SERVER['REQUEST_METHOD'] === 'POST') { $email = $_POST['email']; $password = $_POST['password'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) { $_SESSION['user_id'] = $user['id']; $_SESSION['username'] = $user['name']; header("Location: dashboard.php"); exit; } else { $error = "Invalid credentials"; }}?>
<!DOCTYPE html><html><body> <form method="POST"> <input type="email" name="email" required> <input type="password" name="password" required> <button>Login</button> </form> <?php if (isset($error)) echo "<p>$error</p>"; ?></body></html>
<?php// dashboard.phpif (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit;}?><h1>Welcome, <?= escape($_SESSION['username']) ?>!</h1><a href="logout.php">Logout</a>
<?php// logout.phpsession_destroy();header("Location: login.php");?>REST API
<?phpheader("Content-Type: application/json");
$method = $_SERVER['REQUEST_METHOD'];$path = $_GET['path'] ?? '';
switch ($method) { case 'GET': if ($path === 'users') { $users = $pdo->query("SELECT id, name, email FROM users")->fetchAll(); echo json_encode($users); } break;
case 'POST': $data = json_decode(file_get_contents('php://input'), true); $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->execute([$data['name'], $data['email']]); echo json_encode(['id' => $pdo->lastInsertId()]); break;
default: http_response_code(405); echo json_encode(['error' => 'Method not allowed']);}?>🎯 Quick Reference
| Feature | Syntax |
|---|---|
| Variables | $name = "value"; |
| Arrays | $arr = [1, 2, 3]; |
| Functions | function name() {} |
| Classes | class Name {} |
| Echo | echo "text"; |
| Include | include "file.php"; |
| Session | $_SESSION['key'] |
| GET | $_GET['param'] |
| POST | $_POST['field'] |
Created by cat0x01 🥷🏻