PHP判断远程图片或文件是否存在

PHP判断远程图片是否存在,此方法同样适用于判断远程文件是否存在,这是一种既然有效率且又准确的方法,建议采用此方法,以往使用get_headers()方法判断都是有问题的:

function check_remote_file_exists($url) {
    $curl = curl_init($url);
    //不取回数据
    curl_setopt($curl, CURLOPT_NOBODY, true);
    //发送请求
    $result = curl_exec($curl);
    $found = false;
    if ($result !== false) {
        //检查http响应码是否为200
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  
        if ($statusCode == 200) {
            $found = true;   
        }
    }
    curl_close($curl);
    return $found;
}

从下为调用示例,定义变量用函数返回值赋值:

//函数调用:
$exists = check_remote_file_exists('http://www.baidu.com/img/baidu_sylogo1.gif');
if ($exists) {
    echo '远程图片存在';
} else {
    echo '远程图上不存在';
}

 

posted @ 2015-03-12 21:36  壁虎漫步.  阅读(428)  评论(0编辑  收藏  举报