繁体   English   中英

使用PHP / cURL检查重定向URL的http响应代码

[英]Check http response code of Redirect URL with PHP/cURL

我正在编写一个脚本,该脚本使用curl检查域名数组并返回其http代码。

$urls = array('http://www.example.com', 'http://www.example2.com',  'http://www.example3.com');

$msg = "
<p><strong>URL Error Check</strong></p>
";  

//Set code colours
$code200 = '<span style="color: green;"> OK - ';
$code0 = '<span style="color: red;"> Undefined Error - ';
$code404 = '<span style="color: red;"> File Not Found - ';

foreach($urls as $value){
    $ch = curl_init($value);

        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);
        curl_setopt($ch, CURLOPT_CERTINFO,true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);

    $output = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if($httpcode==301 || $httpcode==302){   
        $redirect = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
        $httpcode .='<br> Redirects to: <span style="color: orange;">'.$redirect;
    }

    curl_close($ch);

    $msg .= $value.": <strong>".${code.$httpcode}.$httpcode."</strong></span><br><br>";
}

echo $msg;

当代码为301或302时,它将在重定向后返回解析URL。 我希望它随后检查最终URL并返回其http代码。

有人可以建议我该怎么做吗?

您可以使用此选项进行curl请求:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

将此选项设置为true时,重定向将不会停止您的请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM