Files
2026-07-10 16:49:32 +02:00

83 lines
1.7 KiB
PHP

<?php
function config(string $key, $default = null)
{
static $config = null;
if ($config === null) {
$config = require __DIR__ . '/../config/config.php';
}
$parts = explode('.', $key);
$value = $config;
foreach ($parts as $part) {
if (!is_array($value) || !array_key_exists($part, $value)) {
return $default;
}
$value = $value[$part];
}
return $value;
}
function e(?string $value): string
{
return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}
function redirect(string $route): never
{
header('Location: index.php?route=' . urlencode($route));
exit;
}
function current_user_id(): ?int
{
return $_SESSION['user_id'] ?? null;
}
function require_login(): void
{
if (!current_user_id()) {
redirect('login');
}
}
function flash(string $key, ?string $message = null): ?string
{
if ($message !== null) {
$_SESSION['flash'][$key] = $message;
return null;
}
$value = $_SESSION['flash'][$key] ?? null;
unset($_SESSION['flash'][$key]);
return $value;
}
function csrf_token(): string
{
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
function csrf_field(): string
{
return '<input type="hidden" name="csrf_token" value="' . e(csrf_token()) . '">';
}
function verify_csrf_token(): void
{
$token = $_POST['csrf_token'] ?? '';
if (!is_string($token) || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) {
http_response_code(419);
echo 'Sicherheitspruefung fehlgeschlagen. Bitte lade die Seite neu.';
exit;
}
}