file_exists
(PHP 4, PHP 5, PHP 7, PHP 8)
file_exists — 檢查檔案或目錄是否存在
說明
file_exists(string
$filename
): bool檢查檔案或目錄是否存在。
參數
-
filename
-
檔案或目錄的路徑。
在 Windows 中要用 //computername/share/filename 或者 \\computername\share\filename 來檢查網路中的共享檔案。
返回值
如果由 filename
指定的檔案或目錄存在則返回
true
,否則返回 false
。
注意:
This function will return
false
for symlinks pointing to non-existing files.
注意:
The check is done using the real UID/GID instead of the effective one.
注意: 因為 PHP 的整數型別是有符號整型而且很多平臺使用 32 位整型,對 2GB 以上的檔案,一些檔案系統函式可能返回無法預期的結果。
範例
示例 #1 測試一個檔案是否存在
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
錯誤/異常
失敗時拋出E_WARNING
警告。
註釋
注意: 此函式的結果會被快取。參見 clearstatcache() 以獲得更多細節。
小技巧
自 PHP 5.0.0 起, 此函式也用於某些 URL 包裝器。請參見 支援的協議和封裝協議以獲得支援 stat() 系列函式功能的包裝器列表。
參見
- is_readable() - 判斷給定檔名是否可讀
- is_writable() - 判斷給定的檔名是否可寫
- is_file() - 判斷給定檔名是否為一個正常的檔案
- file() - 把整個檔案讀入一個陣列中