This article introduces the method of using PHP to determine whether a file exists, supports local and remote file determination, and provides complete calling code and demonstration.
To determine whether the local file exists, you can use the file_exists method to determine.
<?php$file = 'test.jpg'; var_dump(file_exists($file));?>
To determine whether the remote file exists, you cannot use the file_exists method, but get the header of the remote file to determine whether it exists, such as The returned HTTP_CODE is 200 or 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')));?>
<?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)); // falsevar_dump(check_file_exists($file2)); // true?>
This article explains how to determine whether local and remote files exist through php. For more related content, please pay attention to the php Chinese website.
Related recommendations:
Explanation on the method of converting rows and columns of mysql table data
Explanation on the PHP log class
How to combine multiple one-dimensional arrays into a two-dimensional array through PHP
The above is the detailed content of How to determine whether local and remote files exist through php. For more information, please follow other related articles on the PHP Chinese website!