54 lines
1.3 KiB
PHP
54 lines
1.3 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
ini_set('session.cookie_httponly', '1');
|
|
ini_set('session.use_strict_mode', '1');
|
|
|
|
session_start();
|
|
|
|
$config = require '/var/www/TRAILER_TREKKER/private/config.php';
|
|
|
|
function json_response($data, int $code = 200): never {
|
|
http_response_code($code);
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('Cache-Control: no-store');
|
|
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
|
|
function require_login(): void {
|
|
if (empty($_SESSION['tt_logged_in'])) {
|
|
json_response(['ok' => false, 'error' => 'not_authenticated'], 401);
|
|
}
|
|
}
|
|
|
|
function read_json_file(string $path): array {
|
|
if (!file_exists($path)) return [];
|
|
$raw = file_get_contents($path);
|
|
if ($raw === false || trim($raw) === '') return [];
|
|
$data = json_decode($raw, true);
|
|
return is_array($data) ? $data : [];
|
|
}
|
|
|
|
function write_json_file_atomic(string $path, string $json): bool {
|
|
// Ensure directory exists
|
|
$dir = dirname($path);
|
|
if (!is_dir($dir)) {
|
|
if (!mkdir($dir, 0750, true)) return false;
|
|
}
|
|
|
|
$fp = fopen($path, 'c+');
|
|
if ($fp === false) return false;
|
|
|
|
$ok = false;
|
|
if (flock($fp, LOCK_EX)) {
|
|
ftruncate($fp, 0);
|
|
rewind($fp);
|
|
$bytes = fwrite($fp, $json);
|
|
fflush($fp);
|
|
flock($fp, LOCK_UN);
|
|
$ok = ($bytes !== false);
|
|
}
|
|
fclose($fp);
|
|
return $ok;
|
|
} |