如何检查远程URL并防止重定向

时间:2013-10-25 13:08:35

标签: php file testing

我正在尝试检查现有的文件/网址。在线有很多解决方案,但它们无法给我实际的结果。我认为这是因为重定向。所以我使用的代码 https://stackoverflow.com/a/12628971/1312043

它的工作正常,但有时不完美。 我的代码:

function isValidUrl($url){
    // first do some quick sanity checks:
    if(!$url || !is_string($url)){
        return false;
    }
    // quick check url is roughly a valid http request: ( http://blah/... ) 
    if( ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url) ){
        return false;
    }
    // the next bit could be slow:
    if(getHttpResponseCode_using_curl($url) != 200){
        return false;
    }
    // all good!
    return true;
}

function getHttpResponseCode_using_curl($url, $followredirects = false){
    // returns int responsecode, or false (if url does not exist or connection timeout occurs)
    // NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings))
    // if $followredirects == false: return the FIRST known httpcode (ignore redirects)
    // if $followredirects == true : return the LAST  known httpcode (when redirected)
    if(! $url || ! is_string($url)){
        return false;
    }
    $ch = @curl_init($url);
    if($ch === false){
        return false;
    }
    @curl_setopt($ch, CURLOPT_HEADER         ,true);    // we want headers
    @curl_setopt($ch, CURLOPT_NOBODY         ,true);    // dont need body
    @curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true);    // catch output (do NOT print!)
    if($followredirects){
        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,true);
        @curl_setopt($ch, CURLOPT_MAXREDIRS      ,10);  // fairly random number, but could prevent unwanted endless redirects with followlocation=true
    }else{
        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,false);
    }
//      @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5);   // fairly random number (seconds)... but    could prevent waiting forever to get a result
//      @curl_setopt($ch, CURLOPT_TIMEOUT        ,6);   // fairly random number (seconds)... but could prevent waiting forever to get a result
//      @curl_setopt($ch, CURLOPT_USERAGENT      ,"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");   // pretend we're a regular browser
    @curl_exec($ch);
    if(@curl_errno($ch)){   // should be 0
        @curl_close($ch);
        return false;
    }
    $code = @curl_getinfo($ch, CURLINFO_HTTP_CODE); // note: php.net documentation shows this returns a string, but really it returns an int
    @curl_close($ch);
    return $code;
}

例如,如果我想检查此网址:isValidUrl(“http://www.shawonbd.com.be/check_me.php”) 它的反应很好,但错了:( 有没有办法获得完美的结果? 感谢

1 个答案:

答案 0 :(得分:0)

您可以使用get_headers(http://php.net/manual/en/function.get-headers.php)函数。