Bibliothèque PHP
Extraits réutilisables : recherche par mot-clé sur le titre, la description, la catégorie et les tags.
API JSON (pour tests ou intégration) : api/search.php?type=php&q=session
<?php
function startSecureSession(): void {
if (session_status() === PHP_SESSION_ACTIVE) {
return;
}
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => isset($_SERVER['HTTPS']),
'httponly' => true,
'samesite' => 'Lax',
]);
session_start();
}
<?php
$dsn = 'mysql:host=localhost;dbname=ma_base;charset=utf8mb4';
$user = getenv('DB_USER');
$pass = getenv('DB_PASS');
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
<?php
header('Content-Type: application/json; charset=utf-8');
$data = ['ok' => true, 'items' => []];
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// traiter…
$_SESSION['flash_ok'] = 'Enregistré.';
header('Location: ' . $_SERVER['REQUEST_URI'], true, 303);
exit;
}
<?php
echo htmlspecialchars($userInput, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
<?php
$max = 2 * 1024 * 1024;
if (!isset($_FILES['f']) || $_FILES['f']['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('Upload invalide');
}
if ($_FILES['f']['size'] > $max) {
throw new RuntimeException('Fichier trop volumineux');
}
$fi = new finfo(FILEINFO_MIME_TYPE);
$mime = $fi->file($_FILES['f']['tmp_name']);
$allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg'];
if (!isset($allowed[$mime])) {
throw new RuntimeException('Type non autorisé');
}
<?php
$path = __DIR__ . '/data/config.json';
$json = file_get_contents($path);
if ($json === false) {
throw new RuntimeException('Fichier introuvable');
}
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
<?php
declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) {
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_path', '/');
if (PHP_VERSION_ID >= 70300) {
ini_set('session.cookie_samesite', 'Lax');
}
$secure = !empty($_SERVER['HTTPS']) && (string) $_SERVER['HTTPS'] !== 'off';
if (PHP_VERSION_ID >= 70300) {
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => $secure,
'httponly' => true,
'samesite' => 'Lax',
]);
} else {
session_set_cookie_params(0, '/', '', $secure, true);
}
session_start();
}
<?php
declare(strict_types=1);
function cv_db(): PDO
{
static $pdo = null;
if ($pdo instanceof PDO) {
return $pdo;
}
global $config;
$c = $config['db'];
$dsn = sprintf(
'mysql:host=%s;port=%s;dbname=%s;charset=%s',
$c['host'],
$c['port'],
$c['name'],
$c['charset']
);
$pdo = new PDO($dsn, $c['user'], $c['pass'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
return $pdo;
}
<?php
$token = (string) ($_POST['csrf_token'] ?? '');
if ($token === '' || !hash_equals($_SESSION['cv_csrf'] ?? '', $token)) {
http_response_code(403);
echo 'Session expirée ou jeton invalide.';
exit;
}
unset($_SESSION['cv_csrf']);
<?php
/** @return array{0:string,1:string,2:string} cipher, iv b64, tag b64 */
function cv_encrypt(string $plaintext, string $key32): array
{
$iv = random_bytes(12);
$tag = '';
$cipher = openssl_encrypt(
$plaintext,
'aes-256-gcm',
$key32,
OPENSSL_RAW_DATA,
$iv,
$tag,
'',
16
);
if ($cipher === false) {
throw new RuntimeException('Échec du chiffrement.');
}
return [base64_encode($cipher), base64_encode($iv), base64_encode($tag)];
}
<?php
$motDePasse = (string) ($_POST['mot_de_passe'] ?? '');
$email = trim((string) ($_POST['email'] ?? ''));
$hash = '…'; // depuis la base (password_hash)
if ($motDePasse === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$erreur = 'Saisie invalide.';
} elseif (!password_verify($motDePasse, $hash)) {
$erreur = 'Identifiants incorrects.';
} else {
session_regenerate_id(true);
$_SESSION['cv_auth'] = true;
$_SESSION['cv_email'] = $email;
header('Location: questionnaire.php', true, 302);
exit;
}
<?php
$pdo = cv_db();
$email = (string) $_SESSION['cv_email'];
$st = $pdo->prepare(
'SELECT COUNT(*) FROM cv_submissions WHERE email = ? AND cree_le > DATE_SUB(NOW(), INTERVAL 1 HOUR)'
);
$st->execute([$email]);
$n = (int) $st->fetchColumn();
if ($n >= 5) {
http_response_code(429);
echo 'Trop de tentatives récentes. Réessayez plus tard.';
exit;
}
<?php
function cv_is_logged_in(): bool
{
return !empty($_SESSION['cv_auth']) && !empty($_SESSION['cv_email']);
}
function cv_require_login(): void
{
if (!cv_is_logged_in()) {
header('Location: index.php', true, 302);
exit;
}
}