PHP 檔案系統 file_exists() 函式



PHP 檔案系統file_exists()函式用於檢查檔案和目錄是否存在。如果檔案或目錄存在,此函式返回true,否則返回false。

它簡化了路徑驗證,並確認您的PHP指令碼與已存在的檔案或資料夾互動。

語法

以下是PHP檔案系統file_exists()函式的語法:

bool file_exists ( string $filename )

引數

使用file_exists()函式所需的的引數如下:

序號 引數及描述
1

filename(必需)

要檢查的檔案或目錄路徑。

返回值

成功時返回 TRUE,失敗時返回 FALSE。

PHP 版本

file_exists()函式最初作為PHP 4核心的一部分引入,並能很好地與PHP 5、PHP 7、PHP 8一起工作。

示例

這段PHP程式碼演示瞭如何使用PHP檔案系統file_exists()函式來查詢給定的檔案或目錄是否存在。請檢查下面的程式碼示例:

<?php
   $filename = "/PhpProject/sample.txt";

   if(file_exists($filename)) {
      echo "The file $filename exists";
   } else {
      echo "The file $filename does not exist";
   }
?>

輸出

以上程式碼生成以下輸出:

The file /PhpProject/sample.txt exists

示例

這是一個演示如何使用file_exists()函式檢查目錄是否存在。

<?php
   $directory = "/PhpProject/images";

   if(file_exists($directory)) {
      echo "The directory $directory exists";
   } else {
      echo "The directory $directory does not exist";
   }
?> 

輸出

這將產生以下結果:

The directory /PhpProject/images exists

示例

以下程式碼可用於檢查給定目錄中是否存在多個檔案。我們可以透過在路徑末尾使用*(星號)來實現此功能。

<?php
   $path = "/PhpProject/*.txt";

   if(count(glob($path)) > 0) {
      echo "At least one .txt file exists in /PhpProject directory";
   } else {
      echo "No .txt file exists in /PhpProject directory";
   }
?> 

輸出

這將生成以下結果:

At least one .txt file exists in /PhpProject directory

示例

此示例演示瞭如何檢查使用者輸入指定的檔案是否存在。

<?php
   // Assume the user provides the filename as a query parameter
   $userInput = $_GET['filename'];

   if(file_exists($userInput)) {
      echo "The file $userInput exists";
   } else {
      echo "The file $userInput does not exist";
   }
?> 

輸出

這將導致以下結果:

例如,查詢引數如下所示:“https:///mac/index.php?filename=myfile.txt”

The file myfile.txt exists"

注意

使用file_exists()時,請注意安全地處理使用者輸入,以防止諸如目錄遍歷之類的安全問題。

總結

file_exists()函式的多功能性使其能夠用於搜尋檔案和目錄。安全地處理使用者輸入對於避免安全問題非常重要。

php_function_reference.htm
廣告