php判断本地或者远程文件是否存在

发布时间:2020/07/29 作者:天马行空 阅读(745)

1、检查本地文件
file_exists()、is_file()

2、检查远程文件
fopen()、file_get_contents()、fsockopen(),注意在使用fopen需要在php.ini中添加allow_url_fopen = On配置

写一个通用判断函数

function my_file_exists($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);
}


注意,判断文件如果使用"/"代表的不是网站的根目录而是服务器的根目录

关键字php