3807 words
19 minutes
PHP Complete Guide - Server-Side Programming

🐘 PHP Complete Guide - Server-Side Programming#

PHP


📚 Table of Contents#

  1. What is PHP?
  2. Basic Syntax
  3. Variables
  4. Data Types
  5. Operators
  6. Strings
  7. Arrays
  8. Conditionals
  9. Loops
  10. Functions
  11. Superglobals
  12. Forms Handling
  13. File Handling
  14. Sessions and Cookies
  15. MySQL Database
  16. PDO (Secure Database)
  17. Object-Oriented PHP
  18. Error Handling
  19. Security Best Practices
  20. 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) → Database
Browser ← Response ← Server (PHP) ← Database

2. 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 values
echo "Hello", " ", "World";
// print - returns 1, single value
print "Hello World";
// print_r - for arrays (human-readable)
print_r($array);
// var_dump - detailed info (debugging)
var_dump($variable);
// var_export - valid PHP code output
var_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 $message
echo $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(); // 1
echo counter(); // 2
echo 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 constant
echo SITE_NAME;
echo constant("SITE_NAME");
// Check if defined
if (defined("SITE_NAME")) {
echo SITE_NAME;
}
// Magic constants
echo __FILE__; // Full path to file
echo __DIR__; // Directory of file
echo __LINE__; // Current line number
echo __FUNCTION__; // Function name
echo __CLASS__; // Class name
echo __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];
// Object
class Person {}
$obj = new Person();
// NULL
$null = null;
// Resource (file handle, database connection)
$file = fopen("file.txt", "r");
?>

Type Checking#

<?php
$var = "Hello";
// Get type
echo gettype($var); // "string"
// Check specific type
is_string($var); // true
is_int($var); // false
is_float($var); // false
is_bool($var); // false
is_array($var); // false
is_object($var); // false
is_null($var); // false
is_numeric($var); // false
is_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); // true
var_dump($a != $b); // false
// Strict comparison (type must match)
var_dump($a === $b); // false
var_dump($a !== $b); // true
// Other comparisons
var_dump($a > 3); // true
var_dump($a < 3); // false
var_dump($a >= 5); // true
var_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";
// Concatenation
echo $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!";
// Length
echo strlen($str); // 13
// Find position
echo strpos($str, "World"); // 7
echo strrpos($str, "o"); // 8 (last occurrence)
// Extract
echo substr($str, 0, 5); // "Hello"
echo substr($str, -6); // "World!"
// Replace
echo str_replace("World", "PHP", $str); // "Hello, PHP!"
// Case
echo strtoupper($str); // "HELLO, WORLD!"
echo strtolower($str); // "hello, world!"
echo ucfirst("hello"); // "Hello"
echo ucwords("hello world"); // "Hello World"
// Trim
echo 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"
// Reverse
echo strrev("hello"); // "olleh"
// Repeat
echo str_repeat("ha", 3); // "hahaha"
// Padding
echo str_pad("5", 3, "0", STR_PAD_LEFT); // "005"
// Compare
echo strcmp("a", "b"); // -1 (case-sensitive)
echo strcasecmp("A", "a"); // 0 (case-insensitive)
// Check content
var_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 exists
if (isset($user["email"])) {
echo $user["email"];
}
// Null coalescing
echo $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 element
array_pop($arr); // Remove last
array_shift($arr); // Remove first
unset($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];
// Count
echo count($arr); // 8
echo sizeof($arr); // 8
// Search
echo in_array(5, $arr); // true
echo array_search(5, $arr); // 4 (index)
echo array_key_exists("name", $user); // true
// Sort
sort($arr); // Sort ascending
rsort($arr); // Sort descending
asort($arr); // Sort, maintain keys
ksort($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"];
// foreach
foreach ($fruits as $fruit) {
echo $fruit;
}
// With index
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit";
}
// Associative
$user = ["name" => "Ahmed", "age" => 25];
foreach ($user as $key => $value) {
echo "$key: $value";
}
// for loop
for ($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#

<?php
for ($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 reference
foreach ($arr as &$item) {
$item = strtoupper($item);
}
unset($item); // Important: unset reference
?>

break and continue#

<?php
for ($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 function
function greet($name) {
return "Hello, $name!";
}
// Call function
echo greet("Ahmed"); // "Hello, Ahmed!"
// Default parameters
function greet2($name = "Guest") {
return "Hello, $name!";
}
echo greet2(); // "Hello, Guest!"
echo greet2("Ahmed"); // "Hello, Ahmed!"
?>

Type Declarations (PHP 7+)#

<?php
// Parameter types
function add(int $a, int $b): int {
return $a + $b;
}
// Return type
function getName(): string {
return "Ahmed";
}
// Nullable type
function 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 function
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3); // 6
echo 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#

<?php
echo $_SERVER['REQUEST_METHOD']; // GET, POST
echo $_SERVER['HTTP_HOST']; // Domain name
echo $_SERVER['REQUEST_URI']; // /page.php?id=1
echo $_SERVER['REMOTE_ADDR']; // Client IP
echo $_SERVER['HTTP_USER_AGENT']; // Browser info
echo $_SERVER['DOCUMENT_ROOT']; // Server path
echo $_SERVER['PHP_SELF']; // Current script
?>

$_SESSION#

<?php
session_start();
// Set session
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'Ahmed';
// Get session
$userId = $_SESSION['user_id'];
// Check if set
if (isset($_SESSION['user_id'])) {
echo "Logged in!";
}
// Destroy session
session_destroy();
?>
<?php
// Set cookie (before any output!)
setcookie("username", "Ahmed", time() + 86400); // 1 day
// Get cookie
$username = $_COOKIE['username'] ?? 'Guest';
// Delete cookie
setcookie("username", "", time() - 3600);
?>

$_FILES#

<?php
// Handle file upload
if ($_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#

process.php
<?php
if ($_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");
// Append
file_put_contents("file.txt", "New line\n", FILE_APPEND);
// Write with handle
$file = fopen("file.txt", "w"); // w = write, a = append
fwrite($file, "Hello World");
fclose($file);
?>

File Operations#

<?php
// Check if exists
if (file_exists("file.txt")) {
echo "File exists!";
}
// Check if readable/writable
is_readable("file.txt");
is_writable("file.txt");
// Get file info
echo filesize("file.txt"); // Size in bytes
echo filemtime("file.txt"); // Last modified time
echo pathinfo("file.txt", PATHINFO_EXTENSION); // Extension
// Copy, rename, delete
copy("file.txt", "backup.txt");
rename("file.txt", "newname.txt");
unlink("file.txt"); // Delete
// Directory operations
mkdir("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 data
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in']) {
echo "Welcome, " . $_SESSION['username'];
}
// Unset specific session
unset($_SESSION['username']);
// Destroy all session data
session_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 hour
setcookie("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 cookie
setcookie("user", "", time() - 3600);
// Check if cookie exists
if (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 connection
mysqli_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#

<?php
try {
$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#

<?php
class 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#

<?php
class 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
// Interface
interface Drawable {
public function draw();
}
// Abstract class
abstract 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#

<?php
trait 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#

<?php
try {
$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#

<?php
class 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 handler
set_error_handler(function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
// Set exception handler
set_exception_handler(function($e) {
echo "Uncaught exception: " . $e->getMessage();
});
// Error reporting
error_reporting(E_ALL); // All errors
ini_set('display_errors', 0); // Don't show to users
ini_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
// BAD
echo $_GET['name'];
// GOOD
echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
// Even better - use a function
function escape($value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?>

CSRF Protection#

<?php
// Generate token
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// In form
echo '<input type="hidden" name="csrf_token" value="' . $_SESSION['csrf_token'] . '">';
// Validate
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("CSRF token mismatch!");
}
?>

Password Hashing#

<?php
// Hash password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// Verify password
if (password_verify($inputPassword, $hashedPassword)) {
echo "Password is correct!";
}
// Check if rehash needed
if (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 validation
function validateUsername($username) {
return preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username);
}
?>

20. Practical Projects#

Simple Login System#

config.php
<?php
session_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.php
if ($_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.php
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
?>
<h1>Welcome, <?= escape($_SESSION['username']) ?>!</h1>
<a href="logout.php">Logout</a>
<?php
// logout.php
session_destroy();
header("Location: login.php");
?>

REST API#

api.php
<?php
header("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#

FeatureSyntax
Variables$name = "value";
Arrays$arr = [1, 2, 3];
Functionsfunction name() {}
Classesclass Name {}
Echoecho "text";
Includeinclude "file.php";
Session$_SESSION['key']
GET$_GET['param']
POST$_POST['field']

Created by cat0x01 🥷🏻