0

我正在尝试检查现有文件/网址。网上有很多解决方案,但他们不能给我实际的结果。我认为这是因为重定向。所以我使用来自 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;
}

例如,如果我想检查这个 url: isValidUrl(" http://www.shawonbd.com.be/check_me.php ") 它的响应是好的,但它是错误的 :( 有什么方法可以获得完美的结果吗?谢谢

4

1 回答 1

0

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

于 2013-10-25T14:03:17.743 回答