本文介绍使用php判断文件是否存在的方法,支持本地及远程文件判断,提供完整调用代码及演示。

1.判断本地文件是否存在

判断本地文件是否存在,可以使用file_exists方法判断。

<?php
$file = 'test.jpg';
var_dump(file_exists($file));
?>


2.判断远程文件是否存在

判断远程文件是否存在,不能使用file_exists方法,而是获取远程文件的header来判断是否存在,如存在返回的HTTP_CODE是200304

<?php
// 屏蔽域名不存在等访问问题的警告
error_reporting(E_ALL ^ (E_WARNING|E_NOTICE));

$remote_file = 'http://www.csdn/css/logo.png';
$header = get_headers($remote_file, true);
var_dump(isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304')));
?>


3.完整代码

<?php
/**
 * 判断文件是否存在,支持本地及远程文件
 * @param  String  $file 文件路径
 * @return Boolean
 */
function check_file_exists($file){

    // 远程文件
    if(strtolower(substr($file, 0, 4))=='http'){

        $header = get_headers($file, true);

        return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));

    // 本地文件
    }else{
        return file_exists($file);
    }

}

// 屏蔽域名不存在等访问问题的警告
error_reporting(E_ALL ^ (E_WARNING|E_NOTICE));

$file1 = 'test.jpg';
$file2 = 'http://www.csdn/css/logo.png';

var_dump(check_file_exists($file1)); // false
var_dump(check_file_exists($file2)); // true
?>

更多推荐

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