高效判断远程文件是否存在

php php 文件操作 1049      收藏
高效判断远程文件是否存在

/**
 * 高效判断远程文件是否存在
 * @param $file
 * @return bool 存在返回 true 不存在或者其他原因返回false
 */
function remoteFileExist($file)
{
    if(preg_match('/^http:\/\//',$file)){
        //远程文件
        if(ini_get('allow_url_fopen')){
            if(@fopen($file,'r')) return true;
        }
        else{
            $parseurl=parse_url($file);
            $host=$parseurl['host'];
            $path=$parseurl['path'];
            $fp=fsockopen($host,80, $errno, $errstr, 10);
            if(!$fp)return false;
            fputs($fp,"GET {$path} HTTP/1.1 \r\nhost:{$host}\r\n\r\n");
            if(preg_match('/HTTP\/1.1 200/',fgets($fp,1024))) return true;
        }
        return false;
    }
    return file_exists($file);
}