萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP file_exists 函數用法詳解:判斷文件是否存在

PHP file_exists 函數簡介

在 PHP 開發中,經常需要檢查某個文件是否存在於伺服器上。file_exists() 函數正是為此而生,它能快速判斷給定路徑的文件或目錄是否存在,返回布爾值。

語法

bool file_exists ( string $filepath )

參數說明:

  • $filepath:要檢查的文件或目錄路徑(相對路徑或絕對路徑均可)。

返回值: 存在返回 true,否則返回 false。

基本使用範例

<?php
$filepath = './test.php';

if (file_exists($filepath)) {
    echo '文件存在';
} else {
    echo '文件不存在';
}
?>

輸出結果(假設 test.php 存在):

文件存在

進階應用場景

1. 包含文件前檢查

<?php
$configFile = __DIR__ . '/config.php';
if (file_exists($configFile)) {
    require_once $configFile;
} else {
    die('配置文件缺失,請先安裝系統。');
}
?>

2. 上傳文件重命名避免覆蓋

<?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);
?>

常見陷阱與注意事項

  • 緩存問題: PHP 會緩存 file_exists() 的結果。若在同一腳本中先刪除文件再檢查,可能仍返回 true。解決方法:使用 clearstatcache() 清除緩存。
  • 權限限制: 若 PHP 進程無讀取目錄權限,即使文件存在也會返回 false。
  • 區分文件/目錄: file_exists() 對文件和目錄均返回 true。需區分時,配合 is_file() 或 is_dir() 使用。

相關函數對比

函數用途
file_exists()判斷文件/目錄是否存在
is_file()判斷是否為普通文件
is_dir()判斷是否為目錄
is_readable()判斷是否可讀
is_writable()判斷是否可寫

總結

file_exists() 是 PHP 文件操作的基礎函數,掌握其用法與注意事項,能有效避免「文件不存在」導致的致命錯誤,提升代碼健壯性。

copyright © 萬盛學電腦網 all rights reserved