php判断远程文件是否存在的三种方法

时间:2016-08-30
php判断本地服务器文件是否存在可以使用file_exists函数,但是该函数不能用于判断远程文件是否存在,要判断远程文件是否存在,我们可以使用fopen()函数或curl或get_headers函数,本文章向大家介绍fopen()和curl判断远程文件是否存在的实例。

方法一:使用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状态码(并没有下载文件),这样效率更高。