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

时间:2017-01-23 15:05:15

标签: php redirect 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。我想要检查最终的网址并返回它的http代码。

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

1 个答案:

答案 0 :(得分:0)

您可以将此选项用于curl-request:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

如果将此选项设置为true,则在重定向发生时您的请求不会停止。