time() + COOKIE_LIFETIME, 'path' => '/', 'secure' => $https, 'httponly' => false, 'samesite' => 'Lax', ]); } /** Beste unterstützte Sprache aus dem Accept-Language-Header, q-Werte beachtet. */ function accept_language(): ?string { $header = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? ''; if (!is_string($header) || trim($header) === '') { return null; } $candidates = []; foreach (explode(',', $header) as $position => $entry) { $parts = explode(';', trim($entry)); $lang = normalize_lang($parts[0]); if ($lang === null) { continue; } $quality = 1.0; foreach (array_slice($parts, 1) as $parameter) { if (preg_match('/^\s*q\s*=\s*([0-9.]+)\s*$/i', $parameter, $match) === 1) { $quality = (float) $match[1]; } } if ($quality <= 0) { continue; } // Pro Sprache zählt der beste Treffer; bei Gleichstand gewinnt die // Reihenfolge im Header. if (!isset($candidates[$lang]) || $quality > $candidates[$lang][0]) { $candidates[$lang] = [$quality, $position]; } } if ($candidates === []) { return null; } uasort($candidates, static fn (array $a, array $b): int => $b[0] <=> $a[0] ?: $a[1] <=> $b[1]); return (string) array_key_first($candidates); } function redirect_lang(string $lang): never { header('Vary: Accept-Language, Cookie'); header('Location: /' . $lang . '/', true, 302); exit; } /** Explizite Sprachwahl aus der URL, z. B. /de/?lang=en. */ function requested_lang(): ?string { $raw = $_GET['lang'] ?? null; return is_string($raw) ? normalize_lang($raw) : null; } function render_page(string $lang): never { $requested = requested_lang(); if ($requested !== null && $requested !== $lang) { set_lang_cookie($requested); redirect_lang($requested); } if ($requested === $lang) { set_lang_cookie($lang); } $strings = require __DIR__ . '/i18n.php'; $t = $strings[$lang]; $alt = $lang === 'de' ? 'en' : 'de'; header('Content-Type: text/html; charset=utf-8'); require __DIR__ . '/template.php'; exit; }