PHP:检查URL是否重定向?

Ind*_*ial 10 php redirect curl function

我已经实现了一个在每个页面上运行的功能,我希望从未登录的用户进行限制.在他或她未登录的情况下,该功能会自动将访问者重定向到登录页面.

我想创建一个从外部服务器运行的PHP函数,并遍历许多设置URL(具有每个受保护站点的URL的数组),以查看它们是否被重定向.因此,我可以轻松确保每个页面上的保护是否正常运行.

怎么可以这样做?

谢谢.

Ann*_*rom 26

$urls = array(
    'http://www.apple.com/imac',
    'http://www.google.com/'
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

foreach($urls as $url) {
    curl_setopt($ch, CURLOPT_URL, $url);
    $out = curl_exec($ch);

    // line endings is the wonkiest piece of this whole thing
    $out = str_replace("\r", "", $out);

    // only look at the headers
    $headers_end = strpos($out, "\n\n");
    if( $headers_end !== false ) { 
        $out = substr($out, 0, $headers_end);
    }   

    $headers = explode("\n", $out);
    foreach($headers as $header) {
        if( substr($header, 0, 10) == "Location: " ) { 
            $target = substr($header, 10);

            echo "[$url] redirects to [$target]<br>";
            continue 2;
        }   
    }   

    echo "[$url] does not redirect<br>";
}
Run Code Online (Sandbox Code Playgroud)

  • 如果使用`curl_setopt($ handle,CURLOPT_NOBODY,true);`,您还可以节省一些带宽和处理能力.这只会发送HTTP HEAD请求.这样你就不必切断身体了.另见本文:http://schlitt.info/opensource/blog/0606_sending_head_requests_with_extcurl.html (4认同)
  • 您还可以使用curl_getinfo($ ch,CURLINFO_HTTP_CODE)来读取状态代码(301或302) (3认同)

小智 6

在比较我的网址和标头curl的url之后,我使用curl并只获取标头:

                $url="http://google.com";
                $ch = curl_init();

                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_TIMEOUT, '60'); // in seconds
                curl_setopt($ch, CURLOPT_HEADER, 1);
                curl_setopt($ch, CURLOPT_NOBODY, 1);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $res = curl_exec($ch);

                if(curl_getinfo($ch)['url'] == $url){
                    echo "not redirect";
                }else {
                    echo "redirect";
                }
Run Code Online (Sandbox Code Playgroud)