本文介绍使用php判断文件是否存在的方法,支持本地及远程文件判断,提供完整调用代码及演示。
判断本地文件是否存在,可以使用file_exists方法判断。
<?php $file = 'test.jpg'; var_dump(file_exists($file));?>
判断远程文件是否存在,不能使用file_exists方法,而是获取远程文件的header来判断是否存在,如存在返回的HTTP_CODE是200或304。
<?php // 屏蔽域名不存在等访问问题的警告 error_reporting(E_ALL ^ (E_WARNING|E_NOTICE)); $remote_file = ' $header = get_headers($remote_file, true); var_dump(isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304')));?>
<?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.net/css/logo.png';
var_dump(check_file_exists($file1)); // false
var_dump(check_file_exists($file2)); // true
?>| 欢迎光临 一起源码网 (https://www.171739.xyz/) | Powered by Discuz! X3.3 |