🐘 PHP 8+
PHP Complete Cheatsheet
Syntax, OOP, PDO, sessions, Composer and Laravel basics — complete PHP reference.
01
Syntax & Variables
▼
PHPPHP basics
value}"; $msg = 'No interpolation in ' . $name . ' single quotes'; // Heredoc $text = <<
Type juggling
PHP loosely compares types. Use === for strict comparison.
Null coalescing
$val = $arr['key'] ?? 'default'; // PHP 7+
Spaceship op
$a <=> $b: -1, 0, or 1. Used for sorting.
02
Functions
▼
PHPFunctions
function greet(string $name, int $age = 18): string {
return "Hello $name, age $age";
}
// Type declarations (PHP 7+)
function add(int $a, int $b): int { return $a + $b; }
function nullable(?string $s): ?string { return $s; }
// Variadic
function sum(int ...$nums): int { return array_sum($nums); }
sum(1, 2, 3, 4, 5); // 15
// First-class callable (PHP 8.1)
$fn = strlen(...);
$lengths = array_map(strlen(...), ['hello', 'world']);
// Arrow functions (PHP 7.4)
$multiply = fn($x) => $x * 2;
$square = fn($x) => fn($y) => $x * $y; // currying
// Anonymous functions (closures)
$greet = function(string $name) use ($prefix): string {
return "$prefix $name"; // capture $prefix from scope
};
// Match expression (PHP 8.0)
$result = match($status) {
'active' => 'green',
'inactive', 'banned' => 'red',
default => 'gray',
};
03
Arrays
▼
PHPArrays
// Indexed array
$fruits = ['apple', 'banana', 'cherry'];
$fruits[] = 'date'; // append
count($fruits); // 4
// Associative array
$user = [
'name' => 'Ali',
'email' => 'ali@test.com',
'age' => 22,
];
$user['role'] = 'admin';
unset($user['age']);
// Multidimensional
$matrix = [[1,2,3],[4,5,6],[7,8,9]];
$users = [
['id'=>1,'name'=>'Ali'],
['id'=>2,'name'=>'Sara'],
];
// Array functions
array_push($arr, 'item'); array_pop($arr);
array_shift($arr); array_unshift($arr, 'item');
array_merge($a, $b); array_combine($keys, $vals);
array_slice($arr, 1, 3); array_splice($arr, 1, 2);
array_search('val', $arr); in_array('val', $arr);
array_key_exists('key', $arr); isset($arr['key']);
sort($arr); rsort($arr); usort($arr, fn($a,$b) => $a<=>$b);
array_map(fn($x)=>$x*2, $arr);
array_filter($arr, fn($x)=>$x>3);
array_reduce($arr, fn($carry,$x)=>$carry+$x, 0);
array_unique($arr); array_flip($arr); array_reverse($arr);
array_column($users, 'name'); // extract column
04
OOP Classes
▼
PHPObject-Oriented PHP
class BankAccount {
private float $balance;
protected string $owner;
public static int $count = 0;
public function __construct(string $owner, float $initial = 0) {
$this->owner = $owner;
$this->balance = $initial;
self::$count++;
}
public function deposit(float $amount): void {
if ($amount > 0) $this->balance += $amount;
}
public function getBalance(): float { return $this->balance; }
// Magic methods
public function __toString(): string {
return "{$this->owner}: \${$this->balance}";
}
public static function getCount(): int { return self::$count; }
}
class SavingsAccount extends BankAccount {
private float $interestRate;
public function __construct(string $owner, float $rate) {
parent::__construct($owner);
$this->interestRate = $rate;
}
public function addInterest(): void {
$this->deposit($this->balance * $this->interestRate);
}
}
$acc = new BankAccount('Ali', 1000);
$acc->deposit(500);
echo $acc; // Ali: $1500
05
Interfaces & Traits
▼
PHPInterfaces and Traits
// Interface — contract
interface Printable {
public function print(): void;
public function getContent(): string;
}
interface Saveable {
public function save(string $path): bool;
}
class Document implements Printable, Saveable {
public function __construct(private string $content) {}
public function print(): void { echo $this->content; }
public function getContent(): string { return $this->content; }
public function save(string $path): bool { return file_put_contents($path, $this->content) !== false; }
}
// Trait — reusable code snippets
trait Timestamps {
private ?DateTime $createdAt = null;
private ?DateTime $updatedAt = null;
public function touch(): void { $this->updatedAt = new DateTime(); }
public function getCreatedAt(): ?DateTime { return $this->createdAt; }
}
trait SoftDelete {
private ?DateTime $deletedAt = null;
public function delete(): void { $this->deletedAt = new DateTime(); }
public function isDeleted(): bool { return $this->deletedAt !== null; }
}
class Post {
use Timestamps, SoftDelete; // use multiple traits!
public function __construct(public string $title) {}
}
06
Forms & Validation
▼
PHPForms and validation
120) $errors[] = 'Age must be 0-120';
// Prevent XSS
$safe_name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
// CSRF protection
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die('CSRF token mismatch');
}
}
?>
⚠️
NEVER trust user input. Always sanitize, validate and escape. Use htmlspecialchars() before displaying user data.
07
MySQL & PDO
▼
PHPMySQL with PDO
PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// Prepared statement (ALWAYS use for user input — prevents SQL injection!)
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND active = ?');
$stmt->execute([$email, 1]);
$user = $stmt->fetch(); // one row
$users = $stmt->fetchAll(); // all rows
// Named placeholders
$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
$stmt->execute(['name' => $name, 'email' => $email]);
$newId = $pdo->lastInsertId();
// Update / Delete
$pdo->prepare('UPDATE users SET age = ? WHERE id = ?')->execute([$age, $id]);
$pdo->prepare('DELETE FROM users WHERE id = ?')->execute([$id]);
// Transaction
$pdo->beginTransaction();
try { /* operations */ $pdo->commit(); }
catch (Exception $e) { $pdo->rollBack(); throw $e; }
⚠️
ALWAYS use prepared statements. NEVER concatenate user input into SQL queries — that's SQL injection!
08
Sessions & Cookies
▼
PHPSessions and Cookies
'Ali','role'=>'admin'];
unset($_SESSION['temp']);
session_destroy(); // logout
// Secure session config (php.ini or runtime)
ini_set('session.cookie_httponly', 1); // no JS access
ini_set('session.cookie_secure', 1); // HTTPS only
ini_set('session.cookie_samesite', 'Strict');
// Cookies — client-side
setcookie(
'remember_token',
$token,
time() + (30 * 24 * 60 * 60), // 30 days
'/', // path
'', // domain
true, // secure (HTTPS only)
true // httponly (no JS access)
);
$token = $_COOKIE['remember_token'] ?? null;
// Delete cookie
setcookie('remember_token', '', time() - 3600);
09
Composer & Laravel
▼
PHPComposer and Laravel
# Composer — PHP package manager
composer init # create composer.json
composer require laravel/laravel # install package
composer update # update all
composer install # install from composer.lock
composer dump-autoload # regenerate autoload
# Laravel — the most popular PHP framework
composer create-project laravel/laravel myapp
cd myapp && php artisan serve # dev server
# Artisan commands
php artisan make:model User -m # model + migration
php artisan make:controller UserController --resource
php artisan make:request StoreUserRequest
php artisan make:middleware Authenticate
php artisan migrate # run migrations
php artisan migrate:rollback
php artisan tinker # REPL
# Routes (routes/web.php)
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
Route::apiResource('users', UserController::class);
# Eloquent ORM
$users = User::where('active', true)->orderBy('name')->get();
User::create(['name' => 'Ali', 'email' => 'ali@test.com']);
User::find(1)->update(['age' => 23]);
User::find(1)->delete();
10
Mini Quizzes
▼
❓ Quiz 1
Why should you always use PDO prepared statements in PHP?
Prepared statements separate SQL code from user data. The database receives them separately, so user input can never be interpreted as SQL commands. This prevents SQL injection attacks.
❓ Quiz 2
What is a PHP Trait?
Traits are a code reuse mechanism. A class can 'use' multiple traits, getting their methods. Unlike inheritance (one parent only), you can use multiple traits. They solve the problem of code duplication without multiple inheritance.