Syntaxe de base
Structure PHP
<?php
// Commentaire sur une ligne
/* 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 AUTRE_CONSTANTE = 'valeur';
// Affichage
echo $variable;
echo "Texte $variable texte"; // Interpolation
echo 'Texte ' . $variable . ' texte'; // Concaténation
printf("Nombre: %d, Texte: %s", 42, "test");
print_r($array); // Debug array
var_dump($variable); // Debug détaillé
var_export($variable); // Export PHP
Types de données
<?php
// Scalaires
$string = "chaîne";
$int = 42;
$float = 3.14;
$bool = true;
// Composés
$array = [1, 2, 3];
$object = new stdClass();
$callable = function() {};
// Spéciaux
$null = null;
$resource = fopen('file.txt', 'r');
// Type casting
$string = (string) 42; // "42"
$int = (int) "42"; // 42
$float = (float) "3.14"; // 3.14
$bool = (bool) 1; // true
$array = (array) $object;
$object = (object) ['key' => 'value'];
// Vérification de type
is_string($var);
is_int($var);
is_float($var);
is_bool($var);
is_array($var);
is_object($var);
is_null($var);
is_numeric($var);
is_callable($var);
// Type strict (début de fichier)
declare(strict_types=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
<?php
// Arithmétiques
$a + $b; // Addition
$a - $b; // Soustraction
$a * $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
<?php
// If / Else
if ($condition) {
// code
} elseif ($autre_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 ($autre_condition) {
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
<?php
// Création
$array = array(1, 2, 3); // Ancienne syntaxe
$array = [1, 2, 3]; // Syntaxe courte (PHP 5.4+)
$assoc = ['key1' => '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
in_array('value', $array); // Cherche une valeur
array_key_exists('key', $array); // Vérifie si clé existe
// Ajout/Suppression
array_push($array, 'val1', 'val2'); // Ajoute à la fin
$array[] = 'valeur'; // Alternative simple
array_pop($array); // Retire et retourne dernier élément
array_unshift($array, 'val'); // Ajoute au début
array_shift($array); // Retire et retourne premier élément
// Fusion et combinaison
$merged = array_merge($array1, $array2);
$merged = [...$array1, ...$array2]; // Spread operator (PHP 7.4+)
$combined = $array1 + $array2; // Union (garde clés de $array1)
// Extraction et découpage
$slice = array_slice($array, 2, 3); // Extrait 3 éléments depuis position 2
$keys = array_keys($assoc); // Récupère les clés
$values = array_values($assoc); // Récupère les valeurs
$chunk = array_chunk($array, 3); // Divise en sous-tableaux
// Recherche
$key = array_search('value', $array); // Retourne la clé
$filtered = array_filter($array, function($item) {
return $item > 5;
});
// Transformation
$mapped = array_map(function($item) {
return $item * 2;
}, $array);
$reduced = array_reduce($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
array_unique($array); // Retire doublons
array_reverse($array); // Inverse l'ordre
array_flip($array); // Échange clés et valeurs
array_column($multi, 'key'); // Extrait une colonne
array_walk($array, function(&$item, $key) {
$item *= 2; // Modifie chaque élément
});
implode(', ', $array); // Convertit en string
explode(',', $string); // Convertit string en array
array_sum($array); // Somme des valeurs
array_product($array); // Produit des valeurs
array_rand($array); // Clé aléatoire
shuffle($array); // Mélange aléatoirement
Destructuration (PHP 7.1+)
<?php
// Array destructuring
[$a, $b, $c] = [1, 2, 3];
// Avec clés
['nom' => $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
<?php
// Fonction simple
function maFonction() {
return "résultat";
}
// Paramètres
function addition($a, $b) {
return $a + $b;
}
// Paramètres avec types (PHP 7+)
function test(string $nom, int $age): string {
return "$nom a $age ans";
}
// Paramètres par défaut
function saluer($nom = "Visiteur") {
return "Bonjour $nom";
}
// Paramètres optionnels doivent être à la fin
function exemple($requis, $optionnel = "défaut") {
// ...
}
// Paramètres par référence
function incrementer(&$nombre) {
$nombre++;
}
$val = 5;
incrementer($val); // $val vaut maintenant 6
// Nombre variable de paramètres
function somme(...$nombres) {
return array_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
<?php
// Fonction anonyme
$saluer = function($nom) {
return "Bonjour $nom";
};
echo $saluer("Marie");
// Closure avec use
$multiplicateur = 2;
$multiplier = function($nombre) use ($multiplicateur) {
return $nombre * $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 = array_filter($array, fn($x) => $x % 2 === 0);
// First-class callable syntax (PHP 8.1+)
$strlen = strlen(...);
$lengths = array_map($strlen, ['hello', 'world']);
Fonctions utiles
<?php
// Chaînes
strlen($str); // Longueur
strtolower($str); // Minuscules
strtoupper($str); // Majuscules
ucfirst($str); // Première lettre majuscule
ucwords($str); // Première lettre de chaque mot
trim($str); // Retire espaces début/fin
ltrim($str); // Début seulement
rtrim($str); // Fin seulement
str_replace('old', 'new', $str); // Remplace
str_ireplace('old', 'new', $str); // Remplace (insensible casse)
substr($str, 0, 10); // Sous-chaîne
strpos($str, 'needle'); // Position
str_contains($str, 'needle'); // Contient (PHP 8.0+)
str_starts_with($str, 'prefix'); // Commence par (PHP 8.0+)
str_ends_with($str, 'suffix'); // Finit par (PHP 8.0+)
explode(',', $str); // String vers array
implode(',', $array); // Array vers string
sprintf("Format %s %d", "test", 42);
number_format(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
mt_rand(0, 100); // Aléatoire (meilleur)
random_int(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
<?php
// Déclaration de classe
class Personne {
// Propriétés
public string $nom;
private int $age;
protected string $email;
// Constante de classe
public const MAJEUR = 18;
// Propriétés statiques
private static int $compteur = 0;
// Constructeur
public function __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
<?php
class Animal {
protected string $nom;
public function __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
<?php
class Example {
public $public; // Accessible partout
protected $protected; // Classe et enfants
private $private; // Seulement cette classe
// Final - ne peut être overridé
final public function methodeFinale() {
// ...
}
// Abstract - doit être overridé
abstract public function methodeAbstraite();
// Static - appartient à la classe
public static function methodeStatique() {
// Accès avec self::$propriete ou self::methode()
}
// Readonly (PHP 8.1+)
public readonly string $id;
public function __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
<?php
// Interface
interface Volant {
public function voler(): void;
public function atterrir(): void;
}
interface Nageant {
public function nager(): void;
}
// Implémentation multiple
class Canard implements Volant, Nageant {
public function voler(): void {
echo "Le canard vole";
}
public function atterrir(): void {
echo "Le canard atterrit";
}
public function nager(): void {
echo "Le canard nage";
}
}
// Trait (réutilisation de code)
trait Horodatage {
protected DateTime $createdAt;
protected DateTime $updatedAt;
public function setCreatedAt(): void {
$this->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
<?php
class MagicClass {
private array $data = [];
// Getter magique
public function __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 json_encode($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+)
<?php
// Déclaration d'un attribut
#[Attribute]
class Route {
public function __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+)
<?php
// Enum simple
enum Statut {
case BROUILLON;
case PUBLIE;
case ARCHIVE;
}
// Utilisation
$statut = Statut::PUBLIE;
// Enum avec valeur (Backed Enum)
enum StatutHTTP: int {
case OK = 200;
case CREE = 201;
case NON_TROUVE = 404;
case ERREUR_SERVEUR = 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+)
<?php
// Avant PHP 8
class AvantPHP8 {
private string $nom;
private int $age;
public function __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+)
<?php
class User {
public function __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+)
<?php
// Programmation asynchrone légère
$fiber = new Fiber(function (): void {
$value = Fiber::suspend('fiber');
echo "Valeur: $value";
});
$value = $fiber->start(); // 'fiber'
$fiber->resume('test'); // Affiche: Valeur: test
Gestion d’erreurs
Exceptions
<?php
// Try-catch
try {
// Code qui peut lancer une exception
throw new Exception("Erreur");
} catch (Exception $e) {
echo $e->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
<?php
// Error handler personnalisé
set_error_handler(function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
// Exception handler
set_exception_handler(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
<?php
// Lecture
$contenu = file_get_contents('fichier.txt');
$lignes = file('fichier.txt'); // Array de lignes
// Écriture
file_put_contents('fichier.txt', 'Contenu');
file_put_contents('fichier.txt', 'Ajout', FILE_APPEND);
// 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 1\n");
fwrite($handle, "Ligne 2\n");
fclose($handle);
// CSV
$handle = fopen('data.csv', 'r');
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
print_r($data);
}
fclose($handle);
// JSON
$data = ['nom' => 'Test', 'age' => 30];
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents('data.json', $json);
$json = file_get_contents('data.json');
$data = json_decode($json, true); // true = array, false = object
// Vérifications
file_exists('fichier.txt');
is_file('fichier.txt');
is_dir('dossier');
is_readable('fichier.txt');
is_writable('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
<?php
// Formulaire HTML: <input type="file" name="fichier">
if ($_FILES['fichier']['error'] === UPLOAD_ERR_OK) {
$tmpName = $_FILES['fichier']['tmp_name'];
$name = $_FILES['fichier']['name'];
$size = $_FILES['fichier']['size'];
$type = $_FILES['fichier']['type'];
// Validation
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if (in_array($extension, $allowed) && $size < 5000000) {
$newName = uniqid() . '.' . $extension;
$destination = 'uploads/' . $newName;
if (move_uploaded_file($tmpName, $destination)) {
echo "Upload réussi";
}
}
}
// Erreurs possibles
UPLOAD_ERR_OK; // 0 - Succès
UPLOAD_ERR_INI_SIZE; // 1 - Trop grand (php.ini)
UPLOAD_ERR_FORM_SIZE; // 2 - Trop grand (HTML)
UPLOAD_ERR_PARTIAL; // 3 - Upload partiel
UPLOAD_ERR_NO_FILE; // 4 - Pas de fichier
Base de données (PDO)
Connexion et requêtes
<?php
// Connexion MySQL
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mabase;charset=utf8mb4',
'utilisateur',
'motdepasse',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => 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::FETCH_ASSOC); // Array associatif
$user = $stmt->fetch(PDO::FETCH_OBJ); // Objet stdClass
$user = $stmt->fetch(PDO::FETCH_NUM); // Array numérique
$user = $stmt->fetch(PDO::FETCH_CLASS, '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 (user_id) 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::FETCH_COLUMN);
Sessions et Cookies
<?php
// Sessions
session_start();
// Définir
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'jean';
// Lire
$userId = $_SESSION['user_id'] ?? null;
// Vérifier
if (isset($_SESSION['user_id'])) {
// Utilisateur connecté
}
// Supprimer une variable
unset($_SESSION['user_id']);
// Détruire la session
session_destroy();
// Regénérer ID (sécurité)
session_regenerate_id(true);
// Configuration session
ini_set('session.cookie_httponly', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 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
<?php
// Filtres
filter_var('test@example.com', FILTER_VALIDATE_EMAIL);
filter_var('https://example.com', FILTER_VALIDATE_URL);
filter_var('123', FILTER_VALIDATE_INT);
filter_var('3.14', FILTER_VALIDATE_FLOAT);
filter_var('192.168.1.1', FILTER_VALIDATE_IP);
// Nettoyage
filter_var($input, FILTER_SANITIZE_STRING);
filter_var($email, FILTER_SANITIZE_EMAIL);
filter_var($url, FILTER_SANITIZE_URL);
filter_var($int, FILTER_SANITIZE_NUMBER_INT);
// Échappement HTML (contre XSS)
htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
htmlentities($input, ENT_QUOTES, 'UTF-8');
// Protection CSRF
function generateCsrfToken(): string {
return bin2hex(random_bytes(32));
}
function verifyCsrfToken(string $token): bool {
return hash_equals($_SESSION['csrf_token'], $token);
}
// Hachage mot de passe
$hash = password_hash('motdepasse', PASSWORD_DEFAULT);
if (password_verify('motdepasse', $hash)) {
echo "Mot de passe correct";
}
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
// Rehacher avec algorithme plus fort
}
// Hachage générique
$hash = hash('sha256', 'data');
$hash = hash_hmac('sha256', 'data', 'secret_key');
// Random sécurisé
$bytes = random_bytes(32);
$int = random_int(1, 100);
// Protection injection SQL
// TOUJOURS utiliser prepared statements (voir section PDO)
Espaces de noms (Namespaces)
<?php
// Déclaration (début de fichier)
namespace App\Controllers;
class UserController {
// ...
}
// Utilisation
use App\Controllers\UserController;
use App\Models\User as UserModel; // Alias
use App\Services\{EmailService, LogService}; // Groupé
$controller = new UserController();
$user = new UserModel();
// Full qualified name
$user = new \App\Models\User();
// Fonction dans namespace
namespace App\Utils;
function helper() {
return "Helper";
}
// Appel
App\Utils\helper();
// Global namespace
namespace App;
$date = new \DateTime(); // \ pour classe globale
Bonnes pratiques
Standards PSR
<?php
// PSR-1 & PSR-12: Coding Style
namespace Vendor\Package;
use Exception;
class ClassName extends ParentClass implements InterfaceName
{
public const CONSTANT = 'value';
private string $property;
public function methodName(int $arg1, string $arg2): bool
{
if ($arg1 === 0) {
return false;
}
return true;
}
}
// PSR-3: Logger
interface LoggerInterface
{
public function emergency($message, array $context = []);
public function alert($message, array $context = []);
public function critical($message, array $context = []);
public function error($message, array $context = []);
public function warning($message, array $context = []);
public function notice($message, array $context = []);
public function info($message, array $context = []);
public function debug($message, array $context = []);
public function log($level, $message, array $context = []);
}
// PSR-4: Autoloading
// composer.json
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
// Structure: src/Controllers/UserController.php
// Namespace: App\Controllers\UserController
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
password_hash() - Limiter tentatives de connexion
- Activer
session.cookie_httponlyetsession.cookie_secure - Ne jamais afficher erreurs en production
- Garder PHP à jour
Performance
<?php
// Opérateurs ternaires pour valeurs par défaut
$value = $input ?? 'default';
// Null coalescing pour chaînes
$name = $user?->getProfile()?->getName() ?? 'Anonymous';
// Cache avec opcache
opcache_get_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