39853-vm/api/visit-counter.php
2026-05-02 09:04:12 +00:00

50 lines
1.5 KiB
PHP

<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
require_once __DIR__ . '/../db/visit_counter.php';
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
try {
if ($method === 'POST') {
$rawBody = file_get_contents('php://input');
$payload = json_decode(is_string($rawBody) ? $rawBody : '', true);
if (!is_array($payload)) {
$payload = $_POST;
}
$action = is_string($payload['action'] ?? null) ? $payload['action'] : 'ping';
$token = is_string($payload['token'] ?? null) ? $payload['token'] : null;
if ($action === 'forget') {
echo json_encode([
'success' => true,
'counts' => visit_counter_forget($token),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
$tracked = visit_counter_track($token);
echo json_encode([
'success' => true,
'token' => $tracked['token'],
'counts' => $tracked['counts'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
echo json_encode([
'success' => true,
'counts' => visit_counter_snapshot(),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $exception) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'visit_counter_unavailable',
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}