且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 curl 在 PHP 中获取 HTTP 代码

更新时间:2022-04-02 05:45:09

首先确定 URL 是否实际有效(字符串,非空,语法良好),这样可以快速检查服务器端.例如,先执行此操作可以节省大量时间:

First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:

if(!$url || !is_string($url) || ! preg_match('/^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$/i', $url)){
    return false;
}

确保您只获取标题,而不是正文内容:

Make sure you only fetch the headers, not the body content:

@curl_setopt($ch, CURLOPT_HEADER  , true);  // we want headers
@curl_setopt($ch, CURLOPT_NOBODY  , true);  // we don't need body

有关获取 URL 状态 http 代码的更多详细信息,我参考了我发表的另一篇文章(它也有助于以下重定向):

For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):

整体:

$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;