file_exists(string $filename): bool
回傳 true 若 $filename 為檔案或目錄存在;false 否則(含權限不足、路徑錯誤)。
<?php
$file = '/jb51.net/aa/to/foo.txt';
if (file_exists($file)) {
echo "檔案 $file 存在";
} else {
echo "檔案 $file 不存在";
}
// 簡潔寫法
echo file_exists('jb51.net.txt') ? '存在' : '不存在';
?>
//computername/share/filename 或 \\computername\share\filename。is_file/is_dir,結果被快取。寫入/刪除後須 clearstatcache()。if (file_exists($f)) unlink($f); 間隙可能被他進程建立/刪除。關鍵操作請直接嘗試並捕獲錯誤:// 推薦:直接操作,失敗再處理
@unlink($f) || error_log("刪除失敗: $f");
file_exists 無法區分。需搭配 is_file()、is_dir():if (file_exists($path)) {
if (is_file($path)) { /* 檔案邏輯 */ }
elseif (is_dir($path)) { /* 目錄邏輯 */ }
}
if (file_exists($f)) include $f; 可避免警告,但現代框架多用自動載入器(Composer PSR-4),手動檢查較少見。file_exists() 是最通用的存在性檢查,但請記住:快取、競態、不分檔目 三大特性,關鍵路徑請改用「嘗試操作 + 異常處理」模式。