在 PHP 開發中,經常需要檢查某個文件是否存在於伺服器上。file_exists() 函數正是為此而生,它能快速判斷給定路徑的文件或目錄是否存在,返回布爾值。
bool file_exists ( string $filepath )
參數說明:
$filepath:要檢查的文件或目錄路徑(相對路徑或絕對路徑均可)。返回值: 存在返回 true,否則返回 false。
<?php
$filepath = './test.php';
if (file_exists($filepath)) {
echo '文件存在';
} else {
echo '文件不存在';
}
?>
輸出結果(假設 test.php 存在):
文件存在
<?php
$configFile = __DIR__ . '/config.php';
if (file_exists($configFile)) {
require_once $configFile;
} else {
die('配置文件缺失,請先安裝系統。');
}
?>
<?php
$uploadDir = 'uploads/';
$filename = 'avatar.jpg';
$counter = 1;
while (file_exists($uploadDir . $filename)) {
$filename = 'avatar_' . $counter . '.jpg';
$counter++;
}
// 此時 $filename 保證不衝突
move_uploaded_file($_FILES['avatar']['tmp_name'], $uploadDir . $filename);
?>
file_exists() 的結果。若在同一腳本中先刪除文件再檢查,可能仍返回 true。解決方法:使用 clearstatcache() 清除緩存。false。file_exists() 對文件和目錄均返回 true。需區分時,配合 is_file() 或 is_dir() 使用。| 函數 | 用途 |
|---|---|
| file_exists() | 判斷文件/目錄是否存在 |
| is_file() | 判斷是否為普通文件 |
| is_dir() | 判斷是否為目錄 |
| is_readable() | 判斷是否可讀 |
| is_writable() | 判斷是否可寫 |
file_exists() 是 PHP 文件操作的基礎函數,掌握其用法與注意事項,能有效避免「文件不存在」導致的致命錯誤,提升代碼健壯性。