Files
wushu/server_monitor_api.php
2026-03-30 02:35:31 +08:00

80 lines
2.0 KiB
PHP

<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
function getServerLoad() {
$load = sys_getloadavg();
return [
'1min' => round($load[0], 2),
'5min' => round($load[1], 2),
'15min' => round($load[2], 2)
];
}
function getNetworkLatency() {
$hosts = [
'8.8.8.8' => 'Google DNS',
'1.1.1.1' => 'Cloudflare DNS',
'114.114.114.114' => '114 DNS'
];
$results = [];
foreach ($hosts as $ip => $name) {
$start = microtime(true);
$socket = @fsockopen($ip, 53, $errno, $errstr, 2);
$end = microtime(true);
if ($socket) {
fclose($socket);
$latency = round(($end - $start) * 1000, 2);
$results[] = [
'host' => $name,
'ip' => $ip,
'latency' => $latency,
'status' => 'online'
];
} else {
$results[] = [
'host' => $name,
'ip' => $ip,
'latency' => null,
'status' => 'offline'
];
}
}
return $results;
}
function getTimestamp() {
return [
'unix' => time(),
'datetime' => date('Y-m-d H:i:s'),
'timezone' => date_default_timezone_get()
];
}
// 记录请求开始时间
$start_time = microtime(true);
$response = [
'status' => 'success',
'timestamp' => getTimestamp(),
'server' => [
'load' => getServerLoad()
],
'network' => [
'latency' => getNetworkLatency(),
'server_response_time' => round((microtime(true) - $start_time) * 1000, 2) // 服务器响应时间(毫秒)
]
];
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
?>