PHP - 檔案是否存在



在對檔案進行任何處理之前,先檢查你嘗試開啟的檔案是否存在通常非常有用。否則,程式可能會引發執行時異常

PHP 的內建庫在這方面提供了一些實用函式。本章將討論的一些函式包括:

  • file_exists() - 測試檔案是否存在

  • is_file() - 如果 fopen() 返回的控制代碼指向檔案或目錄。

  • is_readable() - 測試你開啟的檔案是否允許讀取資料

  • is_writable() - 測試是否允許向檔案寫入資料

file_exists() 函式

此函式可用於檔案和目錄。它檢查給定的檔案或目錄是否存在。

file_exists(string $filename): bool

此函式唯一的引數是表示檔案/目錄完整路徑的字串。函式根據檔案是否存在返回 true 或 false。

示例

以下程式檢查檔案“hello.txt”是否存在。

<?php
   $filename = 'hello.txt';
   if (file_exists($filename)) {
      $message = "The file $filename exists";
   } else {
      $message = "The file $filename does not exist";
   }
   echo $message;
?>

如果檔案存在於當前目錄中,則訊息為:

The file hello.txt exists

如果不存在,則訊息為:

The file hello.txt does not exist

示例

指向檔案的字串可以具有相對路徑或絕對路徑。假設“hello.txt”檔案位於當前目錄內的“hello”子目錄中。

<?php
   $filename = 'hello/hello.txt';
      if (file_exists($filename)) {
   $message = "The file $filename exists";
   } else {
      $message = "The file $filename does not exist";
   }
   echo $message;
?>

它將產生以下輸出

The file hello/hello.txt exists

示例

嘗試給出如下所示的絕對路徑:

<?php
   $filename = 'c:/xampp/htdocs/hello.txt';
   if (file_exists($filename)) {
      $message = "The file $filename exists";
   } else {
      $message = "The file $filename does not exist";
   }
   echo $message;
?>

它將產生以下輸出

The file c:/xampp/htdocs/hello.txt exists

is_file() 函式

file_exists() 函式對現有檔案和目錄都返回trueis_file() 函式可幫助你確定它是否是檔案。

is_file ( string $filename ) : bool

以下示例顯示了is_file() 函式的工作方式:

<?php
   $filename = 'hello.txt';

   if (is_file($filename)) {
      $message = "$filename is a file";
   } else {
      $message = "$filename is a not a file";
   }
   echo $message;
?>

輸出表明它是一個檔案:

hello.txt is a file

現在,將“$filename”更改為目錄,然後檢視結果:

<?php
   $filename = hello;

   if (is_file($filename)) {
      $message = "$filename is a file";
   } else {
      $message = "$filename is a not a file";
   }
   echo $message;
?>

現在你會被告知“hello”不是檔案。

請注意,is_file() 函式接受一個$filename,並且僅當$filename 是檔案且存在時才返回true

is_readable() 函式

有時,你可能想事先檢查是否可以讀取檔案。is_readable() 函式可以確定這一事實。

is_readable ( string $filename ) : bool

示例

以下是is_readable() 函式工作方式的示例:

<?php
   $filename = 'hello.txt';
   if (is_readable($filename)) {
      $message = "$filename is readable";
   } else {
      $message = "$filename is not readable";
   }
   echo $message;
?>

它將產生以下輸出

hello.txt is readable

is_writable() 函式

你可以使用 is_writable() 函式來檢查檔案是否存在以及是否可以對給定檔案執行寫入操作。

is_writable ( string $filename ) : bool

示例

以下示例顯示了is_writable() 函式的工作方式:

<?php
   $filename = 'hello.txt';

   if (is_writable($filename)) {
      $message = "$filename is writable";
   } else {
      $message = "$filename is not writable";
   }
   echo $message;
?>

對於普通的存檔檔案,程式會指出它是可寫的。但是,將其屬性更改為“只讀”並執行程式。現在你得到:

hello.txt is writable
廣告