PHP 8.x : Guide de référence rapide
Syntaxe de base
Structure PHP
Commentaire
multi-lignes /
/
Commentaire de documentation (PHPDoc)
@param string $param Description
@return bool
/
// Instructions
echo "Hello World";
print "Alternative";
// Variables
$variable = "valeur";
$nombre = 42;
$float = 3.14;
$boolean = true;
$null = null;
// Constantes
define('CONSTANTE', 'valeur');
const AUTRECONSTANTE = 'valeur';
// Affichage
echo $variable;
echo "Texte $variable texte"; // Interpolation
echo 'Texte ' . $variable . ' texte'; // Concaténation
printf("Nombre: %d, Texte: %s", 42, "test");
printr($array); // Debug array
vardump($variable); // Debug détaillé
varexport($variable); // Export PHP
Types de données
'value'];
// Vérification de type
isstring($var);
isint($var);
isfloat($var);
isbool($var);
isarray($var);
isobject($var);
isnull($var);
isnumeric($var);
iscallable($var);
// Type strict (début de fichier)
declare(stricttypes=1);
// Type hints (PHP 7+)
function test(string $str, int $num): bool {
return true;
}
// Types nullable (PHP 7.1+)
function test(?string $str): ?int {
return null;
}
// Union types (PHP 8.0+)
function test(int|float $number): string|int {
return "résultat";
}
// Mixed type (PHP 8.0+)
function test(mixed $anything): mixed {
return $anything;
}
Opérateurs
$b; // Multiplication
$a / $b; // Division
$a % $b; // Modulo
$a $b; // Puissance (PHP 5.6+)
++$a; // Pré-incrémentation
$a++; // Post-incrémentation
--$a; // Pré-décrémentation
$a--; // Post-décrémentation
// Affectation
$a = 5;
$a += 3; // $a = $a + 3
$a -= 3;
$a = 3;
$a /= 3;
$a %= 3;
$a .= 'texte'; // Concaténation
// Comparaison
$a == $b; // Égalité (conversion type)
$a === $b; // Identité stricte
$a != $b; // Différent
$a !== $b; // Non identique
$a < $b;
$a > $b;
$a <= $b;
$a >= $b;
$a <=> $b; // Spaceship (PHP 7+): -1, 0, ou 1
// Logiques
$a && $b; // ET (and)
$a || $b; // OU (or)
!$a; // NON (not)
$a and $b; // ET (priorité basse)
$a or $b; // OU (priorité basse)
$a xor $b; // XOR exclusif
// Null coalescing (PHP 7+)
$var = $a ?? $b; // $a si existe et non null, sinon $b
$var = $a ?? $b ?? $c ?? 'défaut';
// Null coalescing assignment (PHP 7.4+)
$var ??= 'valeur par défaut'; // Assigne si $var est null
// Nullsafe operator (PHP 8.0+)
$value = $obj?->method()?->property;
// Ternaire
$var = $condition ? $vrai : $faux;
$var = $condition ?: 'défaut'; // Court si $condition est truthy
// Chaînes
$a . $b; // Concaténation
$a .= $b; // Concaténation et affectation
// Tableaux
$a + $b; // Union
$a == $b; // Égalité
$a === $b; // Identité
Structures de contrôle
condition) {
// code
} else {
// code
}
// If inline
$var = $condition ? 'vrai' : 'faux';
// Switch
switch ($variable) {
case 'valeur1':
// code
break;
case 'valeur2':
case 'valeur3':
// code pour valeur2 ou valeur3
break;
default:
// code par défaut
}
// Match (PHP 8.0+) - Plus strict et retourne une valeur
$result = match($variable) {
'valeur1' => 'résultat1',
'valeur2', 'valeur3' => 'résultat2',
default => 'résultat par défaut',
};
// While
while ($condition) {
// code
}
// Do While
do {
// code
} while ($condition);
// For
for ($i = 0; $i < 10; $i++) {
// code
}
// Foreach
foreach ($array as $value) {
// code
}
foreach ($array as $key => $value) {
// code
}
// Foreach par référence
foreach ($array as &$value) {
$value = 2; // Modifie l'array original
}
unset($value); // Important de nettoyer la référence
// Break et Continue
foreach ($array as $value) {
if ($condition) {
continue; // Passe à l'itération suivante
}
if ($autrecondition) {
break; // Sort de la boucle
}
}
// Break/Continue avec niveau
foreach ($array1 as $item1) {
foreach ($array2 as $item2) {
break 2; // Sort des 2 boucles
}
}
Tableaux
Manipulation de tableaux
'value1', 'key2' => 'value2'];
$mixed = [1, 'deux', 3 => 'trois', 'key' => 'value'];
// Accès
$value = $array[0];
$value = $assoc['key1'];
$value = $array[0] ?? 'défaut'; // Avec null coalescing
// Modification
$array[0] = 'nouvelle valeur';
$array[] = 'ajout en fin';
// Tableaux multidimensionnels
$multi = [
['a', 'b', 'c'],
['d', 'e', 'f'],
];
$value = $multi[0][1]; // 'b'
// Fonctions essentielles
count($array); // Nombre d'éléments
sizeof($array); // Alias de count()
empty($array); // Vérifie si vide
isset($array[0]); // Vérifie si index existe
unset($array[0]); // Supprime un élément
inarray('value', $array); // Cherche une valeur
arraykeyexists('key', $array); // Vérifie si clé existe
// Ajout/Suppression
arraypush($array, 'val1', 'val2'); // Ajoute à la fin
$array[] = 'valeur'; // Alternative simple
arraypop($array); // Retire et retourne dernier élément
arrayunshift($array, 'val'); // Ajoute au début
arrayshift($array); // Retire et retourne premier élément
// Fusion et combinaison
$merged = arraymerge($array1, $array2);
$merged = [...$array1, ...$array2]; // Spread operator (PHP 7.4+)
$combined = $array1 + $array2; // Union (garde clés de $array1)
// Extraction et découpage
$slice = arrayslice($array, 2, 3); // Extrait 3 éléments depuis position 2
$keys = arraykeys($assoc); // Récupère les clés
$values = arrayvalues($assoc); // Récupère les valeurs
$chunk = arraychunk($array, 3); // Divise en sous-tableaux
// Recherche
$key = arraysearch('value', $array); // Retourne la clé
$filtered = arrayfilter($array, function($item) {
return $item > 5;
});
// Transformation
$mapped = arraymap(function($item) {
return $item 2;
}, $array);
$reduced = arrayreduce($array, function($carry, $item) {
return $carry + $item;
}, 0);
// Tri
sort($array); // Tri croissant (réindexe)
rsort($array); // Tri décroissant (réindexe)
asort($array); // Tri croissant (garde clés)
arsort($array); // Tri décroissant (garde clés)
ksort($array); // Tri par clés croissant
krsort($array); // Tri par clés décroissant
usort($array, function($a, $b) {
return $a <=> $b; // Tri personnalisé
});
// Autres fonctions utiles
arrayunique($array); // Retire doublons
arrayreverse($array); // Inverse l'ordre
arrayflip($array); // Échange clés et valeurs
arraycolumn($multi, 'key'); // Extrait une colonne
arraywalk($array, function(&$item, $key) {
$item = 2; // Modifie chaque élément
});
implode(', ', $array); // Convertit en string
explode(',', $string); // Convertit string en array
arraysum($array); // Somme des valeurs
arrayproduct($array); // Produit des valeurs
arrayrand($array); // Clé aléatoire
shuffle($array); // Mélange aléatoirement
Destructuration (PHP 7.1+)
$nom, 'age' => $age] = $personne;
// Skip d'éléments
[, , $c] = [1, 2, 3]; // $c = 3
// Dans foreach
foreach ($users as ['id' => $id, 'name' => $name]) {
echo "$id: $name";
}
// Swap de variables
[$a, $b] = [$b, $a];
Fonctions
Déclaration et appel
sum($nombres);
}
somme(1, 2, 3, 4); // 10
// Named arguments (PHP 8.0+)
function creerUtilisateur($nom, $age, $email) {
// ...
}
creerUtilisateur(
nom: "Jean",
email: "jean@example.com",
age: 30
);
// Return types
function getNumber(): int {
return 42;
}
function getUser(): ?array { // Nullable
return null;
}
function getValue(): int|float { // Union type
return 3.14;
}
// Void return (PHP 7.1+)
function logMessage(string $msg): void {
echo $msg;
// Pas de return ou return; seulement
}
// Never return (PHP 8.1+)
function redirect(): never {
header('Location: /');
exit;
}
Fonctions anonymes et closures
$multiplicateur;
};
// Modifier variable externe (par référence)
$compteur = 0;
$incrementer = function() use (&$compteur) {
$compteur++;
};
$incrementer();
// Arrow functions (PHP 7.4+)
$multiplier = fn($x) => $x 2;
$somme = fn($a, $b) => $a + $b;
// Arrow function avec capture automatique
$multiplicateur = 2;
$multiplier = fn($x) => $x $multiplicateur; // Pas besoin de use()
// Callback
$array = [1, 2, 3, 4, 5];
$pairs = arrayfilter($array, fn($x) => $x % 2 === 0);
// First-class callable syntax (PHP 8.1+)
$strlen = strlen(...);
$lengths = arraymap($strlen, ['hello', 'world']);
Fonctions utiles
replace('old', 'new', $str); // Remplace
strireplace('old', 'new', $str); // Remplace (insensible casse)
substr($str, 0, 10); // Sous-chaîne
strpos($str, 'needle'); // Position
strcontains($str, 'needle'); // Contient (PHP 8.0+)
strstartswith($str, 'prefix'); // Commence par (PHP 8.0+)
strendswith($str, 'suffix'); // Finit par (PHP 8.0+)
explode(',', $str); // String vers array
implode(',', $array); // Array vers string
sprintf("Format %s %d", "test", 42);
numberformat(1234.567, 2, ',', ' '); // "1 234,57"
// Dates
date('Y-m-d H:i:s'); // Format date
time(); // Timestamp Unix
strtotime('2024-12-18'); // String vers timestamp
mktime(0, 0, 0, 12, 18, 2024); // Créer timestamp
// DateTime (orienté objet)
$date = new DateTime('2024-12-18');
$date->format('Y-m-d');
$date->modify('+1 day');
$interval = new DateInterval('P1D'); // 1 jour
$date->add($interval);
$diff = $date1->diff($date2);
// Mathématiques
abs($num); // Valeur absolue
ceil($num); // Arrondi supérieur
floor($num); // Arrondi inférieur
round($num, 2); // Arrondi (2 décimales)
min($a, $b, $c); // Minimum
max($a, $b, $c); // Maximum
rand(0, 100); // Aléatoire
mtrand(0, 100); // Aléatoire (meilleur)
randomint(0, 100); // Aléatoire cryptographique (PHP 7+)
sqrt($num); // Racine carrée
pow($base, $exp); // Puissance
pi(); // Pi
Programmation Orientée Objet
Classes et objets
construct(string $nom, int $age) {
$this->nom = $nom;
$this->age = $age;
self::$compteur++;
}
// Méthodes
public function getNom(): string {
return $this->nom;
}
public function getAge(): int {
return $this->age;
}
public function setAge(int $age): void {
if ($age > 0) {
$this->age = $age;
}
}
// Méthode statique
public static function getCompteur(): int {
return self::$compteur;
}
// Méthode magique toString
public function toString(): string {
return "{$this->nom} ({$this->age} ans)";
}
// Destructeur
public function destruct() {
// Nettoyage si nécessaire
}
}
// Utilisation
$personne = new Personne("Jean", 30);
echo $personne->nom; // Jean
echo $personne->getAge(); // 30
$personne->setAge(31);
echo $personne; // Jean (31 ans)
echo Personne::MAJEUR; // 18
echo Personne::getCompteur(); // 1
Héritage
construct(string $nom) {
$this->nom = $nom;
}
public function parler(): string {
return "L'animal fait un bruit";
}
}
class Chien extends Animal {
private string $race;
public function construct(string $nom, string $race) {
parent::construct($nom); // Appel constructeur parent
$this->race = $race;
}
// Override
public function parler(): string {
return "Woof!";
}
public function getRace(): string {
return $this->race;
}
}
$chien = new Chien("Rex", "Labrador");
echo $chien->parler(); // Woof!
Visibilité et modificateurs
construct(string $id) {
$this->id = $id; // Peut être assigné une fois
}
}
// Classe finale - ne peut être étendue
final class ClasseFinale {
// ...
}
// Classe abstraite - ne peut être instanciée
abstract class ClasseAbstraite {
abstract protected function methodeRequise(): string;
public function methodeConcrète(): void {
echo $this->methodeRequise();
}
}
Interfaces et Traits
createdAt = new DateTime();
}
public function getCreatedAt(): DateTime {
return $this->createdAt;
}
}
trait Validation {
public function valider(array $data): bool {
// Logique de validation
return true;
}
}
class Article {
use Horodatage, Validation;
private string $titre;
public function construct(string $titre) {
$this->titre = $titre;
$this->setCreatedAt();
}
}
// Résolution de conflits de traits
trait A {
public function test() {
echo "A";
}
}
trait B {
public function test() {
echo "B";
}
}
class C {
use A, B {
B::test insteadof A; // Utilise B::test
A::test as testA; // Alias pour A::test
}
}
Méthodes magiques
get(string $name) {
return $this->data[$name] ?? null;
}
// Setter magique
public function set(string $name, $value): void {
$this->data[$name] = $value;
}
// Isset magique
public function isset(string $name): bool {
return isset($this->data[$name]);
}
// Unset magique
public function unset(string $name): void {
unset($this->data[$name]);
}
// Appel de méthode inexistante
public function call(string $name, array $args) {
echo "Méthode $name appelée avec: " . implode(', ', $args);
}
// Appel de méthode statique inexistante
public static function callStatic(string $name, array $args) {
echo "Méthode statique $name appelée";
}
// Conversion en string
public function toString(): string {
return jsonencode($this->data);
}
// Invocation comme fonction
public function invoke($param) {
echo "Objet invoqué avec $param";
}
// Clone
public function clone() {
// Comportement lors du clonage
}
// Debug info
public function debugInfo(): array {
return ['debug' => $this->data];
}
}
// Utilisation
$obj = new MagicClass();
$obj->nom = "Test"; // set
echo $obj->nom; // get
isset($obj->nom); // isset
unset($obj->nom); // unset
$obj->methodeInexistante(); // call
echo $obj; // toString
$obj('param'); // invoke
$clone = clone $obj; // clone
Fonctionnalités PHP 8+
Attributs (PHP 8.0+)
construct(
public string $path,
public string $method = 'GET'
) {}
}
// Utilisation
#[Route('/api/users', 'GET')]
class UserController {
#[Route('/api/users/{id}', 'GET')]
public function show(int $id) {
// ...
}
}
// Lecture des attributs via Reflection
$reflection = new ReflectionClass(UserController::class);
$attributes = $reflection->getAttributes(Route::class);
foreach ($attributes as $attribute) {
$route = $attribute->newInstance();
echo $route->path; // /api/users
}
Énumérations (PHP 8.1+)
TROUVE = 404;
case ERREURSERVEUR = 500;
}
$code = StatutHTTP::OK->value; // 200
// Enum avec méthodes
enum Couleur: string {
case ROUGE = '#FF0000';
case VERT = '#00FF00';
case BLEU = '#0000FF';
public function label(): string {
return match($this) {
self::ROUGE => 'Rouge',
self::VERT => 'Vert',
self::BLEU => 'Bleu',
};
}
public static function fromLabel(string $label): self {
return match($label) {
'Rouge' => self::ROUGE,
'Vert' => self::VERT,
'Bleu' => self::BLEU,
};
}
}
// From/tryFrom pour backed enums
$statut = StatutHTTP::from(200); // OK
$statut = StatutHTTP::tryFrom(999); // null si invalide
// Cases
$tous = StatutHTTP::cases(); // Array de tous les cas
Constructor Property Promotion (PHP 8.0+)
construct(string $nom, int $age) {
$this->nom = $nom;
$this->age = $age;
}
}
// Avec PHP 8
class AvecPHP8 {
public function construct(
private string $nom,
private int $age,
public readonly string $id = ''
) {}
}
$user = new AvecPHP8('Jean', 30);
Readonly Properties (PHP 8.1+)
construct(
public readonly string $id,
public readonly string $email
) {}
}
$user = new User('123', 'test@example.com');
// $user->id = '456'; // Erreur: Cannot modify readonly property
// Readonly class (PHP 8.2+)
readonly class Point {
public function construct(
public int $x,
public int $y
) {}
}
Fibers (PHP 8.1+)
start(); // 'fiber'
$fiber->resume('test'); // Affiche: Valeur: test
Gestion d’erreurs
Exceptions
getMessage();
} finally {
// Toujours exécuté
echo "Nettoyage";
}
// Multiple catch
try {
// ...
} catch (InvalidArgumentException $e) {
// Gestion spécifique
} catch (RuntimeException $e) {
// Autre gestion
} catch (Exception $e) {
// Gestion générique
}
// Catch multiple types (PHP 7.1+)
try {
// ...
} catch (InvalidArgumentException | RuntimeException $e) {
// Gestion commune
}
// Non-capturing catches (PHP 8.0+)
try {
// ...
} catch (SomeException) {
// Pas besoin de la variable $e
echo "Erreur";
}
// Création d'exception personnalisée
class MonException extends Exception {
public function construct(
string $message = "",
int $code = 0,
?Throwable $previous = null
) {
parent::_construct($message, $code, $previous);
}
public function messagePersonnalise(): string {
return "Erreur: {$this->message}";
}
}
// Lancer
throw new MonException("Quelque chose s'est mal passé");
// Hiérarchie d'exceptions
class ValidationException extends Exception {}
class EmailInvalideException extends ValidationException {}
// Propriétés d'exception
try {
throw new Exception("Message", 404);
} catch (Exception $e) {
echo $e->getMessage(); // Message
echo $e->getCode(); // 404
echo $e->getFile(); // Fichier
echo $e->getLine(); // Ligne
echo $e->getTrace(); // Stack trace
echo $e->getTraceAsString();
}
Gestion d’erreurs
errorhandler(function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
// Exception handler
setexceptionhandler(function($exception) {
echo "Exception non capturée: " . $exception->getMessage();
// Logger, envoyer email, etc.
});
// Error (PHP 7+)
try {
undefinedFunction();
} catch (Error $e) {
echo "Erreur fatale capturée";
}
// Throwable (PHP 7+) - Interface parente de Exception et Error
try {
// ...
} catch (Throwable $t) {
// Capture tout
}
Fichiers et système
Manipulation de fichiers
getcontents('fichier.txt');
$lignes = file('fichier.txt'); // Array de lignes
// Écriture
fileputcontents('fichier.txt', 'Contenu');
fileputcontents('fichier.txt', 'Ajout', FILEAPPEND);
// Lecture/Écriture avec fopen
$handle = fopen('fichier.txt', 'r'); // r, w, a, r+, w+, a+
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
// Écriture
$handle = fopen('fichier.txt', 'w');
fwrite($handle, "Ligne 1n");
fwrite($handle, "Ligne 2n");
fclose($handle);
// CSV
$handle = fopen('data.csv', 'r');
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
printr($data);
}
fclose($handle);
// JSON
$data = ['nom' => 'Test', 'age' => 30];
$json = jsonencode($data, JSONPRETTYPRINT | JSONUNESCAPEDUNICODE);
fileputcontents('data.json', $json);
$json = filegetcontents('data.json');
$data = jsondecode($json, true); // true = array, false = object
// Vérifications
fileexists('fichier.txt');
isfile('fichier.txt');
isdir('dossier');
isreadable('fichier.txt');
iswritable('fichier.txt');
filesize('fichier.txt');
filemtime('fichier.txt'); // Timestamp dernière modification
// Manipulation
copy('source.txt', 'destination.txt');
rename('ancien.txt', 'nouveau.txt');
unlink('fichier.txt'); // Suppression
mkdir('dossier', 0755, true); // true = récursif
rmdir('dossier');
// Chemins
basename('/path/to/file.txt'); // file.txt
dirname('/path/to/file.txt'); // /path/to
pathinfo('/path/to/file.txt'); // Array avec dirname, basename, extension
realpath('../file.txt'); // Chemin absolu
Upload de fichiers
if ($FILES['fichier']['error'] === UPLOADERROK) {
$tmpName = $FILES['fichier']['tmpname'];
$name = $FILES['fichier']['name'];
$size = $FILES['fichier']['size'];
$type = $FILES['fichier']['type'];
// Validation
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$extension = strtolower(pathinfo($name, PATHINFOEXTENSION));
if (inarray($extension, $allowed) && $size < 5000000) {
$newName = uniqid() . '.' . $extension;
$destination = 'uploads/' . $newName;
if (moveuploadedfile($tmpName, $destination)) {
echo "Upload réussi";
}
}
}
// Erreurs possibles
UPLOADERROK; // 0 - Succès
UPLOADERRINISIZE; // 1 - Trop grand (php.ini)
UPLOADERRFORMSIZE; // 2 - Trop grand (HTML)
UPLOADERRPARTIAL; // 3 - Upload partiel
UPLOADERRNOFILE; // 4 - Pas de fichier
Base de données (PDO)
Connexion et requêtes
ERRMODE => PDO::ERRMODEEXCEPTION,
PDO::ATTRDEFAULTFETCHMODE => PDO::FETCHASSOC,
PDO::ATTREMULATEPREPARES => false,
]
);
} catch (PDOException $e) {
die("Erreur connexion: " . $e->getMessage());
}
// SELECT
$stmt = $pdo->query('SELECT FROM users');
$users = $stmt->fetchAll();
// Fetch modes
$user = $stmt->fetch(PDO::FETCHASSOC); // Array associatif
$user = $stmt->fetch(PDO::FETCHOBJ); // Objet stdClass
$user = $stmt->fetch(PDO::FETCHNUM); // Array numérique
$user = $stmt->fetch(PDO::FETCHCLASS, 'User'); // Objet de classe
// Prepared statements (TOUJOURS utiliser pour variables)
$stmt = $pdo->prepare('SELECT FROM users WHERE id = ?');
$stmt->execute([1]);
$user = $stmt->fetch();
// Named parameters
$stmt = $pdo->prepare('SELECT FROM users WHERE email = :email AND active = :active');
$stmt->execute(['email' => 'test@example.com', 'active' => 1]);
$user = $stmt->fetch();
// INSERT
$stmt = $pdo->prepare('INSERT INTO users (nom, email, age) VALUES (?, ?, ?)');
$stmt->execute(['Jean', 'jean@example.com', 30]);
$lastId = $pdo->lastInsertId();
// UPDATE
$stmt = $pdo->prepare('UPDATE users SET age = :age WHERE id = :id');
$stmt->execute(['age' => 31, 'id' => 1]);
$affected = $stmt->rowCount();
// DELETE
$stmt = $pdo->prepare('DELETE FROM users WHERE id = ?');
$stmt->execute([1]);
// Transactions
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare('INSERT INTO users (nom) VALUES (?)');
$stmt->execute(['User1']);
$stmt = $pdo->prepare('INSERT INTO logs (userid) VALUES (?)');
$stmt->execute([$pdo->lastInsertId()]);
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
// Boucle sur résultats
$stmt = $pdo->query('SELECT FROM users');
while ($user = $stmt->fetch()) {
echo $user['nom'];
}
// Fetch column
$stmt = $pdo->query('SELECT email FROM users');
$emails = $stmt->fetchAll(PDO::FETCHCOLUMN);
Sessions et Cookies
start();
// Définir
$SESSION['userid'] = 123;
$SESSION['username'] = 'jean';
// Lire
$userId = $SESSION['userid'] ?? null;
// Vérifier
if (isset($SESSION['userid'])) {
// Utilisateur connecté
}
// Supprimer une variable
unset($SESSION['userid']);
// Détruire la session
sessiondestroy();
// Regénérer ID (sécurité)
sessionregenerateid(true);
// Configuration session
iniset('session.cookiehttponly', 1);
iniset('session.useonlycookies', 1);
iniset('session.cookiesecure', 1); // HTTPS seulement
// Cookies
// Définir (nom, valeur, expiration, path, domain, secure, httponly)
setcookie('user', 'jean', time() + 3600, '/', '', true, true);
// Lire
$user = $COOKIE['user'] ?? null;
// Supprimer
setcookie('user', '', time() - 3600);
Sécurité
Validation et nettoyage
var('test@example.com', FILTERVALIDATEEMAIL);
filtervar('https://example.com', FILTERVALIDATEURL);
filtervar('123', FILTERVALIDATEINT);
filtervar('3.14', FILTERVALIDATEFLOAT);
filtervar('192.168.1.1', FILTERVALIDATEIP);
// Nettoyage
filtervar($input, FILTERSANITIZESTRING);
filtervar($email, FILTERSANITIZEEMAIL);
filtervar($url, FILTERSANITIZEURL);
filtervar($int, FILTERSANITIZENUMBERINT);
// Échappement HTML (contre XSS)
htmlspecialchars($input, ENTQUOTES, 'UTF-8');
htmlentities($input, ENTQUOTES, 'UTF-8');
// Protection CSRF
function generateCsrfToken(): string {
return bin2hex(randombytes(32));
}
function verifyCsrfToken(string $token): bool {
return hashequals($SESSION['csrftoken'], $token);
}
// Hachage mot de passe
$hash = passwordhash('motdepasse', PASSWORDDEFAULT);
if (passwordverify('motdepasse', $hash)) {
echo "Mot de passe correct";
}
if (passwordneedsrehash($hash, PASSWORDDEFAULT)) {
// Rehacher avec algorithme plus fort
}
// Hachage générique
$hash = hash('sha256', 'data');
$hash = hashhmac('sha256', 'data', 'secretkey');
// Random sécurisé
$bytes = randombytes(32);
$int = randomint(1, 100);
// Protection injection SQL
// TOUJOURS utiliser prepared statements (voir section PDO)
Espaces de noms (Namespaces)
Bonnes pratiques
Standards PSR
Sécurité
- Toujours valider et nettoyer les entrées
- Utiliser prepared statements pour SQL
- Échapper les sorties HTML
- Utiliser HTTPS
- Implémenter protection CSRF
- Hacher les mots de passe avec
passwordhash() - Limiter tentatives de connexion
- Activer
session.cookiehttponlyetsession.cookiesecure - Ne jamais afficher erreurs en production
- Garder PHP à jour
Performance
getProfile()?->getName() ?? 'Anonymous';
// Cache avec opcache
opcacheget_status();
// Éviter requêtes N+1
// Charger relations en une requête plutôt qu'en boucle
// Utiliser générateurs pour grandes données
function getLargeData() {
foreach ($data as $item) {
yield $item; // Itération sans charger tout en mémoire
}
}
---
Version: PHP 8.3 | Ressources: php.net, PSR standards