pridany serverovy skript pre logovanie meranych hodnot
This commit is contained in:
88
server/log.php
Normal file
88
server/log.php
Normal file
@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
function respondJson(int $statusCode, array $payload): void
|
||||
{
|
||||
http_response_code($statusCode);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode($payload) . PHP_EOL;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
header('Allow: POST');
|
||||
respondJson(405, [
|
||||
'success' => false,
|
||||
'error' => 'Method Not Allowed',
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$levels = [];
|
||||
foreach (['level1', 'level2', 'level3', 'level4'] as $name) {
|
||||
if (!array_key_exists($name, $_POST)) {
|
||||
$levels[$name] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_array($_POST[$name])) {
|
||||
respondJson(400, [
|
||||
'success' => false,
|
||||
'error' => 'Invalid value for ' . $name,
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$value = trim((string) $_POST[$name]);
|
||||
if ($value !== '0' && $value !== '1') {
|
||||
respondJson(400, [
|
||||
'success' => false,
|
||||
'error' => 'Invalid value for ' . $name,
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$levels[$name] = (int) $value;
|
||||
}
|
||||
|
||||
$record = [
|
||||
'timestamp' => date('c'),
|
||||
'level1' => (int) $levels['level1'],
|
||||
'level2' => (int) $levels['level2'],
|
||||
'level3' => (int) $levels['level3'],
|
||||
'level4' => (int) $levels['level4'],
|
||||
];
|
||||
|
||||
$dataDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'data';
|
||||
if (!is_dir($dataDir)) {
|
||||
if (!mkdir($dataDir, 0755, true) && !is_dir($dataDir)) {
|
||||
respondJson(500, [
|
||||
'success' => false,
|
||||
'error' => 'Failed to create data directory',
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
$filename = $dataDir . DIRECTORY_SEPARATOR . date('Y') . '.jsonl';
|
||||
$json = json_encode($record);
|
||||
if ($json === false) {
|
||||
respondJson(500, [
|
||||
'success' => false,
|
||||
'error' => 'Failed to encode record',
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$written = file_put_contents($filename, $json . PHP_EOL, FILE_APPEND | LOCK_EX);
|
||||
if ($written === false) {
|
||||
respondJson(500, [
|
||||
'success' => false,
|
||||
'error' => 'Failed to write log file',
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
respondJson(200, [
|
||||
'success' => true,
|
||||
]);
|
||||
Reference in New Issue
Block a user