Initial habit tracker project
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user