
<?php
header('Content-Type: application/json; charset=utf-8');
$storeFile = __DIR__ . '/../data/visitors_online.json';
$windowSeconds = 120; $maxKeepSeconds = 1800;
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; $ua = $_SERVER['HTTP_USER_AGENT'] ?? ''; $key = hash('sha256', $ip . '|' . substr($ua,0,120)); $now = time();
$data = file_exists($storeFile) ? json_decode((string)file_get_contents($storeFile), true) : []; if (!is_array($data)) $data = [];
$data[$key] = $now; foreach ($data as $k => $ts) { if (!is_int($ts) && !ctype_digit((string)$ts)) unset($data[$k]); elseif ($now - (int)$ts > $maxKeepSeconds) unset($data[$k]); }
file_put_contents($storeFile, json_encode($data));
$online = 0; foreach ($data as $ts) if ($now - (int)$ts <= $windowSeconds) $online++;
echo json_encode(['ok'=>true,'online'=>$online]);
