本文介紹使用php判斷檔案是否存在的方法,支援本地及遠程檔案判斷,提供完整調用代碼及示範。
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)); // falsevar_dump(check_file_exists($file2)); // true?>
本篇講解了通過php判斷本地及遠程檔案是否存在 ,更多相關內容請關注php中文網。