1.判断本地文件是否存在
判断本地文件是否存在,可以使用file_exists方法判断。
<?php $file = 'test.jpg'; var_dump(file_exists($file)); ?>
2.判断远程文件是否存在
判断远程文件是否存在,不能使用file_exists方法,而是获取远程文件的header来判断是否存在,如存在返回的HTTP_CODE是200或304。
<?php // 屏蔽域名不存在等访问问题的警告 error_reporting(E_ALL ^ (E_WARNING|E_NOTICE)); $remote_file = 'http://www.csdn.net/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.net/css/logo.png'; var_dump(check_file_exists($file1)); // false var_dump(check_file_exists($file2)); // true ?>
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/232900.html原文链接:https://javaforall.net