file_exists() 是 PHP 檢查文件或目錄是否存在的最基礎函數,但其行為在不同操作系統、流封裝器、權限情況下有細微差異。本文全面解析用法、返回值、緩存機制、網絡路徑支持與避坑指南。
file_exists(string $filename): bool
// 返回值
// true - 文件或目錄存在
// false - 不存在、權限不足、掛載點不可用、路徑過長等
<?php
$filename = '/var/www/html/config.php';
if (file_exists($filename)) {
echo "文件 $filename 存在";
} else {
echo "文件 $filename 不存在";
}
// 直接輸出布爾值 (1/空字符串)
echo file_exists('test.txt'); // 存在輸出 1,不存在輸出空字符串
?>
Windows 環境下支持 UNC 路徑訪問網絡共享:
<?php
// 兩種寫法均可
$unc1 = '//SERVER/share/file.txt'; // 標準 UNC
$unc2 = '\\\\SERVER\\share\\file.txt'; // 轉義反斜杠
if (file_exists($unc1)) {
echo "網絡文件可訪問";
}
// 注意:需要運行 PHP 的用戶有網絡共享讀取權限
// IIS 環境下通常是 IUSR 或 ApplicationPoolIdentity
?>
關鍵特性:PHP 為性能緩存 file_exists() 等 stat 族函數的結果。
<?php
$file = 'test.txt';
file_put_contents($file, 'content');
var_dump(file_exists($file)); // true
unlink($file);
var_dump(file_exists($file)); // true (緩存未更新!)
// 清除緩存
clearstatcache();
var_dump(file_exists($file)); // false (正確)
// 針對特定文件清除緩存 (PHP 5.3+)
clearstatcache(true, $file);
?>
| 場景 | 問題 | 解決 |
|---|---|---|
| 文件剛創建/刪除 | 緩存導致結果不準 | 操作後調用 clearstatcache() |
| NFS/網絡文件系統 | 屬性緩存延遲 | 掛載參數 noac / 手動 clearstatcache |
| 符號鏈接 | 檢測鏈接本身而非目標 | 用 is_link()+readlink() 組合判斷 |
| open_basedir 限制 | 路徑超出範圍返回 false | 檢查 php.ini open_basedir 設置 |
| 大小寫敏感性 | Linux 區分大小寫,Windows 不區分 | 統一路徑大小寫規範 |
| 流封裝器 | 支持 https:// ftp:// 等但行為異常 | 本地文件優先用實際路徑 |
<?php
$file = 'example.txt';
is_file($file); // 是否普通文件
is_dir($file); // 是否目錄
is_link($file); // 是否符號鏈接
is_readable($file); // 是否可讀 (考慮權限、open_basedir)
is_writable($file); // 是否可寫
is_executable($file); // 是否可執行
filesize($file); // 文件大小 (字節)
filemtime($file); // 最後修改時間 (時間戳)
fileatime($file); // 最後訪問時間
filectime($file); // inode 變更時間
fileperms($file); // 權限掩碼
filetype($file); // file/dir/link/fifo/block/char/socket
// 統一獲取所有信息
$stat = stat($file); // 數字鍵
$stat = fstat($fp); // 基於打開句柄
$lstat = lstat($file); // 不跟隨符號鏈接
?>
<?php
function safeFileExists(string $path, bool $clearCache = true): bool {
// 1. 路徑標準化
$path = realpath($path) ?: $path;
// 2. open_basedir 預檢
if (ini_get('open_basedir')) {
$realPath = realpath($path);
if ($realPath === false) return false;
$openBasedir = explode(PATH_SEPARATOR, ini_get('open_basedir'));
$allowed = false;
foreach ($openBasedir as $dir) {
if (str_starts_with($realPath, rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR)) {
$allowed = true;
break;
}
}
if (!$allowed) return false;
}
// 3. 檢查存在性
if ($clearCache) clearstatcache(true, $path);
return file_exists($path);
}
// 使用
if (safeFileExists('/var/www/config.php')) {
// 安全讀取
}
?>
clearstatcache(),批量操作前清除一次is_file()/is_dir() 替代 file_exists() (語義更明確)auto_globals_jit 可微幅提升超全局變量訪問速度