方法一:使用curl判断远程文件是否存在:

function remoteFileExists($url) {
    $curl = curl_init($url);

    //don\'t fetch the actual page, you only want to check the connection is ok
    curl_setopt($curl, CURLOPT_NOBODY, true);

    //do request
    $result = curl_exec($curl);

    $ret = false;

    //if request did not fail
    if ($result !== false) {
        //if request was ok, check response code
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);

    return $ret;
}

$exists = remoteFileExists(\'http://manongjc.com/favicon.ico\');
if ($exists) {
    echo \'文件存在\';
} else {
    echo \'文件不存在\';   
}

 

方法二:使用fopen()判断远程文件是否存在

$file = \'http://manongjc.com/favicon.ico\';
$file_exists = (@fopen($file, \"r\")) ? true : false;

 

方法三:使用fopen()判断远程文件是否存在

function remote_file_exists($url){
   return(bool)preg_match(\'~HTTP/1\\.\\d\\s+200\\s+OK~\', @current(get_headers($url)));
}  
/*  http://www.manongjc.com/article/1415.html */
$ff = \"http://manongjc.com/favicon.ico\";
    if(remote_file_exists($ff)){
        echo \"file exist!\";
    }
    else{
        echo \"file not exist!!!\";
    }

function is_url($url)
{
    $array= get_headers($url);
    $h= $array[0];
    return( strlen($h==3) && ($h[2]==\'2\' || $h[2]==\'3\'));
}

注意:上面三种方法都是判断HTTP状态码(并没有下载文件),这样效率更高。

收藏 打印