PHP 获取网站状态代码,支持 SSL 证书验证
以下是一个使用 PHP 获取网站 URL 状态的示例代码,它通过使用 cURL 库来处理 SSL 证书:
<?php
function getWebsiteStatus($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
return 'Error: ' . $error;
} else {
if ($httpCode >= 200 && $httpCode < 300) {
return 'Website is live';
} else {
return 'Website is down (HTTP code: $httpCode)';
}
}
}
$url = 'https://www.example.com';
echo getWebsiteStatus($url);
?>
在上面的示例中,getWebsiteStatus 函数使用 cURL 库来执行 HTTP HEAD 请求,并检查返回的 HTTP 代码来确定网站的状态。同时,设置了 CURLOPT_SSL_VERIFYPEER 和 CURLOPT_SSL_VERIFYHOST 选项为 true,以启用 SSL 证书验证。
请注意,如果你想检查使用自签名证书或其他不受信任的证书的网站,请确保你的服务器上安装了相关的根证书或禁用 SSL 证书验证。
原文地址: https://www.cveoy.top/t/topic/bx21 著作权归作者所有。请勿转载和采集!