<?php
// 监测网站的可用性
function checkWebsiteAvailability($url) {
$headers = @get_headers($url);
if ($headers === false) {
return [
'status' => 'unreachable',
'http_code' => null,
'message' => 'Unable to reach the URL.'
];
}
$statusLine = $headers[0];
preg_match('/HTTP\/\d\.\d (\d+)/', $statusLine, $matches);
if (isset($matches[1])) {
$httpCode = intval($matches[1]);
return [
'status' => ($httpCode >= 200 && $httpCode < 300) ? 'available' : 'unavailable',
'http_code' => $httpCode,
'message' => $statusLine
];
}
return [
'status' => 'unknown',
'http_code' => null,
'message' => 'Unable to determine status from headers.'
];
}
// 监测的 URL
$url = 'http://example.com'; // 替换为你想要监测的 URL
// 获取并输出网站的可用性
$result = checkWebsiteAvailability($url);
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
?>