vdepontac

Créateur digital & développeur


Design Lab

Bibliothèque PHP

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

Session sécurisée

Sécurité

Démarrer une session PHP avec des paramètres cohérents (cookie HttpOnly, SameSite).

session cookie httponly samesite auth
<?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();
}

Connexion PDO MySQL

Base de données

Connexion PDO avec exceptions et UTF-8.

pdo mysql sql utf8 connexion
<?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,
]);

Réponse JSON API

API

En-têtes JSON + encodage UTF-8 pour une API REST.

json header api rest utf-8
<?php
header('Content-Type: application/json; charset=utf-8');
$data = ['ok' => true, 'items' => []];
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);

Post/Redirect/Get (PRG)

Formulaires

Éviter le re-post du formulaire après traitement.

prg redirect post formulaire flash
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // traiter…
    $_SESSION['flash_ok'] = 'Enregistré.';
    header('Location: ' . $_SERVER['REQUEST_URI'], true, 303);
    exit;
}

Échappement HTML

Sécurité

Afficher du texte utilisateur sans XSS.

htmlspecialchars xss échappement sécurité
<?php
echo htmlspecialchars($userInput, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

Vérification upload fichier

Fichiers

Contrôles MIME, taille et extension.

upload fichier mime validation
<?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é');
}

En-têtes e-mail basiques

E-mail

From encodé et Content-Type texte UTF-8.

mail email header utf-8
<?php
$from = 'contact@example.com';
$headers = [
    'From: Site <' . $from . '>',
    'MIME-Version: 1.0',
    'Content-Type: text/plain; charset=UTF-8',
];
// mail($to, $subject, $body, implode("\r\n", $headers));

Lire un fichier JSON

Données

Chargement avec gestion d’erreur.

json file decode config
<?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);

Carte verte — démarrage session (WAMP / sous-dossiers)

Projet Carte verte

Session stricte, cookie HttpOnly, path « / », SameSite Lax si disponible (extrait de bootstrap.php).

carte verte session cookie_path samesite wamp bootstrap
<?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();
}

Carte verte — PDO MySQL réutilisable (cv_db)

Projet Carte verte

Instance unique de PDO, DSN construit depuis la config (host, port, charset).

carte verte pdo mysql singleton dsn charset
<?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;
}

Carte verte — vérification jeton CSRF (POST)

Projet Carte verte

Comparaison timing-safe avec hash_equals, invalidation du jeton après usage.

carte verte csrf hash_equals post session sécurité
<?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']);

Carte verte — chiffrement AES-256-GCM (données sensibles)

Projet Carte verte

openssl_encrypt, IV 12 octets, tag d’authentification (extrait logique crypto.php).

carte verte aes gcm openssl chiffrement iv tag
<?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)];
}

Carte verte — connexion mot de passe (password_verify)

Projet Carte verte

Validation e-mail, vérif du hash stocké, régénération d’ID de session après succès.

carte verte password_verify session_regenerate_id email filter login
<?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;
}

Carte verte — limitation d’envois par e-mail (anti-spam)

Projet Carte verte

Comptage sur la dernière heure avant insertion (extrait submit.php).

carte verte rate limit spam sql count 429
<?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;
}

Carte verte — page protégée (redirection si non connecté)

Projet Carte verte

Garde simple sur $_SESSION avant affichage ou traitement.

carte verte auth session redirect middleware
<?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;
    }
}


Warning: Undefined variable $layoutMode in /home/u579348626/domains/vdepontac.fr/public_html/inc/layout-bottom.php on line 44