Files
wevads-platform/scripts/api_sessions-stats.php
2026-02-26 04:53:11 +01:00

67 lines
2.0 KiB
PHP
Executable File

<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$sessionsPath = '/opt/wevads/storage/sessions';
$accessLog = '/var/log/apache2/wevads_access.log';
// Compter sessions PHP actives (< 5 min)
$sessions = glob($sessionsPath . '/sess_*');
$activeSessions = 0;
foreach ($sessions as $file) {
if ((time() - filemtime($file)) < 300) $activeSessions++;
}
// Compter visiteurs HTTP actifs (logs Apache, dernières 5 min)
$activeVisitors = 0;
$visitorIPs = [];
$cutoff = time() - 300;
if (file_exists($accessLog) && is_readable($accessLog)) {
$fp = @fopen($accessLog, 'r');
if ($fp) {
fseek($fp, -min(filesize($accessLog), 100000), SEEK_END);
fgets($fp);
while (!feof($fp)) {
$line = fgets($fp);
if (preg_match('/^(\S+) \S+ \S+ \[([^\]]+)\]/', $line, $m)) {
$ip = $m[1];
$date = DateTime::createFromFormat('d/M/Y:H:i:s O', $m[2]);
if ($date && $date->getTimestamp() >= $cutoff) {
$visitorIPs[$ip] = true;
}
}
}
fclose($fp);
}
}
$activeVisitors = count($visitorIPs);
// IP courante
$currentIP = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
// GeoIP simple
function getCountry($ip) {
if (in_array($ip, ['127.0.0.1', '::1'])) return ['country' => 'Local', 'code' => 'LO'];
$ctx = stream_context_create(['http' => ['timeout' => 1]]);
$json = @file_get_contents("http://ip-api.com/json/{$ip}?fields=country,countryCode", false, $ctx);
if ($json) {
$data = json_decode($json, true);
if ($data) return ['country' => $data['country'] ?? 'Unknown', 'code' => $data['countryCode'] ?? 'XX'];
}
return ['country' => 'Unknown', 'code' => 'XX'];
}
$geo = getCountry($currentIP);
echo json_encode([
'sessions' => $activeSessions,
'visitors' => $activeVisitors,
'total_sessions' => count($sessions),
'current_ip' => $currentIP,
'country' => $geo['country'],
'country_code' => $geo['code']
]);