PHP 檔案系統 is_readable() 函式



PHP 檔案系統is_readable() 函式用於檢查給定檔案是否存在以及是否可讀。該函式有助於透過確保程式碼僅嘗試讀取存在且可訪問的檔案來使程式碼免於錯誤。

語法

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

bool is_readable ( string $filename )

引數

以下是is_readable() 函式所需的引數:

序號 引數及描述
1

$filename(必填)

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

返回值

is_readable() 函式如果路徑是檔案或目錄則返回 true,否則返回 FALSE。

PHP 版本

is_readable() 函式最初作為 PHP 4 核心的一部分引入,並且與 PHP 5、PHP 7 和 PHP 8 相容。

示例

我們使用了 PHP 檔案系統is_readable() 函式來檢查給定路徑是否指向檔案或目錄。

<?php
   // Mention the file path here
   $filename = '/PhpProjects/myfile.txt';
   if (is_readable($filename)) {
       echo 'The file is readable.';
   } else {
       echo 'The file is not readable.';
   }
?>

輸出

以下是以下程式碼的結果:

The file is readable.

示例

此 PHP 示例將執行操作以使用is_readable() 函式檢查給定檔案是否可讀。我們將使用陣列來儲存多個檔案的路徑。

<?php
   //mention your file path here
   $files = ['/PhpProjects/myfile.txt', '/PhpProjects/sample.txt', '/PhpProjects/newfile.txt'];

   foreach ($files as $file) {
       if (is_readable($file)) {
           echo "The file $file is readable.\n";
       } else {
           echo "The file $file is not readable.\n";
       }
   }
?> 

輸出

這將產生以下結果:

The file /PhpProjects/myfile.txt is readable.
The file /PhpProjects/sample.txt is readable.
The file /PhpProjects/newfile.txt is readable.

示例

在此 PHP 程式碼中,我們將使用is_readable() 函式來檢查給定目錄是否具有讀取其內容的許可權。因此,如果它可讀,則將返回 true,否則返回 false。

<?php
   // Mention the relative path here
   $directory = '/PhpProjects';

   if (is_readable($directory)) {
      echo "The directory is readable.";
   } else {
      echo "The directory is not readable.";
   }
?> 

輸出

這將生成以下結果:

The directory is readable.

示例

在此 PHP 程式碼中,我們將使用is_readable() 函式在嘗試開啟檔案之前檢查檔案是否可讀。因此,如果它可讀,則將返回 true,否則將返回 false。

<?php
   // Mention multiple paths here
   $file = '/PhpProjects/myfile.txt';

   if (is_readable($file)) {
       $handle = fopen($file, 'r');
       if ($handle) {
           echo "The file is open for reading.";
           fclose($handle);
       }
   } else {
       echo "The file is not readable.";
   }
?> 

輸出

這將產生以下輸出:

The file is open for reading.

注意

此函式可以針對目錄返回 true 結果。在這種情況下,您可以使用 is_dir() 來區分檔案和目錄。

總結

is_readable() 函式是一個功能強大的函式,用於檢查給定檔案或目錄是否可讀。此方法在開啟檔案之前用於驗證檔案是否可訪問以讀取,從而避免不必要的工作。

php_function_reference.htm
廣告