我正在使用 CURL 来获取站点的状态,如果它是向上/向下或重定向到另一个站点。我想让它尽可能精简,但效果不佳。
<?php
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode;
?>
我把它封装在一个函数中。它工作正常,但性能不是最好的,因为它会下载整个页面,如果我删除 $output = curl_exec($ch);
它总是返回 0
.
有谁知道如何让性能更好?
最佳答案
首先确定 URL 是否有效(字符串,非空,语法良好),这样可以快速检查服务器端。例如,首先这样做可以节省大量时间:
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
return false;
}
确保只获取标题,而不是正文内容:
@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body
有关获取 URL 状态 http 代码的更多详细信息,请参阅我发布的另一篇文章(它也有助于以下重定向):
整体而言:
$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo 'HTTP code: ' . $httpcode;
关于php - 使用 curl 在 PHP 中获取 HTTP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11797680/