Home >Backend Development >PHP Tutorial >Example analysis of how PHP determines whether local and remote files exist
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 = ' $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 ?>
The above is the detailed content of Example analysis of how PHP determines whether local and remote files exist. For more information, please follow other related articles on the PHP Chinese website!