file_exists() 回傳 falseis_file()、is_dir() 同樣失效PHP safe_mode(已移除於 PHP 5.4)或 open_basedir 限制腳本可存取的目錄樹。若目標路徑不在允許清單中,檔案系統函數會回傳 false 並可能觸發警告。
// 錯誤:相對路徑可能受 open_basedir 影響
$file = 'config.php';
if (file_exists($file)) ...
// 正確:基於文檔根目錄的絕對路徑
$file = $_SERVER['DOCUMENT_ROOT'] . '/config.php';
if (file_exists($file)) ...
// 適用於 include/require(它們不受 open_basedir 限制同樣路徑)
include $_SERVER['DOCUMENT_ROOT'] . '/config.php';
$_SERVER['DOCUMENT_ROOT'] 回傳網站根目錄絕對路徑(不含尾部斜線),如 /var/www/html 或 D:/www/htdocs。
檔案/目錄權限導致 PHP 進程用戶(如 www-data、apache、nginx)無讀取/執行權限。
ls -la /path/to/file.php
# -rw------- 1 user user 123 Jan 1 00:00 file.php // 其他用戶無讀取權限
# 給予其他用戶讀取權限
chmod 644 /path/to/file.php
# 目錄需執行權限才能遍歷
chmod 755 /path/to/dir
# 遞迴修正整個專案
chown -R www-data:www-data /var/www/html
find /var/www/html -type d -exec chmod 755 {} \;
find /var/www/html -type f -exec chmod 644 {} \;
// 程式碼寫死小寫
include 'config.php';
// 實際檔案:Config.php (Linux 找不到)
解決:統一使用小寫檔名,或用 realpath() 解析實際路徑。
// 錯誤:混用斜線、相對路徑基準不清
$path = '..\config\file.php';
// 正確:使用 DIRECTORY_SEPARATOR、dirname(__FILE__) 或 __DIR__
$path = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'file.php';
// PHP 5.3+ 推薦
$path = __DIR__ . '/../config/file.php'; // PHP 內部自動處理斜線
PHP 為效能快取 stat() 系統呼叫結果(file_exists、filesize、filemtime 等)。檔案外部變更後,PHP 可能仍回傳舊結果。
file_exists($file); // true
unlink($file); // 外部或同腳本刪除
file_exists($file); // 仍回傳 true (快取)!
clearstatcache(); // 清除快取
file_exists($file); // false
或使用 clearstatcache(true, $file) (PHP 5.3+) 清除特定檔案快取。
function debugFileExists($path) {
echo "Path: $path\n";
echo "DOCUMENT_ROOT: " . $_SERVER['DOCUMENT_ROOT'] . "\n";
echo "realpath: " . (realpath($path) ?: 'false') . "\n";
echo "is_readable: " . (is_readable($path) ? 'true' : 'false') . "\n";
echo "file_exists: " . (file_exists($path) ? 'true' : 'false') . "\n";
echo "is_file: " . (is_file($path) ? 'true' : 'false') . "\n";
echo "perms: " . substr(sprintf('%o', fileperms($path)), -4) . "\n";
echo "uid/gid: " . fileowner($path) . '/' . filegroup($path) . "\n";
echo "current user: " . get_current_user() . "\n";
}