許多開發者以為 is_file() 和 file_exists() 只是功能重疊,實際上它們在快取機制上有本質差異,這在高併發或檔案頻繁變動的場景下會導致嚴重 Bug。
<?php
$filename = 'test.txt';
// 確保測試檔案存在
file_put_contents($filename, 'test');
// 第一次檢測
if (is_file($filename)) {
echo "$filename exists!\n";
} else {
echo "$filename no exists!\n";
}
// 模擬 10 秒後檔案被刪除
sleep(10); // 在此期間手動刪除 test.txt
// 第二次檢測
if (is_file($filename)) {
echo "$filename exists!\n";
} else {
echo "$filename no exists!\n";
}
test.txt exists!
test.txt exists! <-- 錯誤!檔案已刪除但仍回傳 true
test.txt exists!
test.txt no exists! <-- 正確反映檔案已刪除
若必須使用 is_file()、is_dir()、filesize() 等依賴 stat 快取的函數,在檔案可能被外部修改的情況下,請手動清除快取:
clearstatcache(); // 清除所有 stat 快取
// 或 PHP 5.3+ 針對特定檔案清除
clearstatcache(true, $filename);
| 函數 | 有快取 | 適用場景 |
|---|---|---|
| file_exists() | ❌ 否 | 即時檢查檔案是否存在 |
| is_file() | ✅ 是 | 效能敏感、確定檔案不會外部變動 |
| is_dir() | ✅ 是 | 效能敏感、確定目錄不會外部變動 |
| filesize() | ✅ 是 | 效能敏感、確定檔案大小不會變動 |
| filemtime() | ✅ 是 | 效能敏感、確定修改時間不會變動 |
file_exists() 進行存在性檢查,避免快取陷阱is_file() 並搭配 clearstatcache()clearstatcache()file_exists()