首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP file_exists() 函數完整指南:檢查檔案與目錄存在性

     編輯:PHP 綜合知識

函數簽名

file_exists(string $filename): bool

回傳 true 若 $filename 為檔案或目錄存在;false 否則(含權限不足、路徑錯誤)。

基本範例

<?php
$file = '/jb51.net/aa/to/foo.txt';
if (file_exists($file)) {
    echo "檔案 $file 存在";
} else {
    echo "檔案 $file 不存在";
}

// 簡潔寫法
echo file_exists('jb51.net.txt') ? '存在' : '不存在';
?>

Windows 網路共享路徑

  • UNC 格式://computername/share/filename 或 \\computername\share\filename。
  • 需執行 PHP 的使用者具備共享讀取權限。

常見誤區與最佳實踐

  1. 快取機制:同 is_file/is_dir,結果被快取。寫入/刪除後須 clearstatcache()。
  2. 競態條件 (TOCTOU):if (file_exists($f)) unlink($f); 間隙可能被他進程建立/刪除。關鍵操作請直接嘗試並捕獲錯誤:
// 推薦:直接操作,失敗再處理
@unlink($f) || error_log("刪除失敗: $f");
  1. 區分檔案/目錄:file_exists 無法區分。需搭配 is_file()、is_dir():
if (file_exists($path)) {
    if (is_file($path)) { /* 檔案邏輯 */ }
    elseif (is_dir($path)) { /* 目錄邏輯 */ }
}
  1. include/require 前檢查:if (file_exists($f)) include $f; 可避免警告,但現代框架多用自動載入器(Composer PSR-4),手動檢查較少見。

結語

file_exists() 是最通用的存在性檢查,但請記住:快取、競態、不分檔目 三大特性,關鍵路徑請改用「嘗試操作 + 異常處理」模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved