PHP 檔案系統 is_dir() 函式



PHP 檔案系統 is_dir() 函式用於檢查路徑是否為目錄。它需要指定並傳遞要檢查的路徑。如果路徑是目錄,則該方法返回 true,否則返回 false。

語法

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

bool is_dir(string $path)

引數

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

序號 引數及描述
1

$path(必需)

這是您要檢查的路徑。

返回值

函式 is_dir() 如果路徑是目錄則返回 true,否則返回 FALSE。

PHP 版本

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

示例

我們使用了 PHP 檔案系統 is_dir() 函式來檢查給定的路徑是目錄還是檔案。

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

   if (is_dir($path)) {
      echo "The path is a directory.";
   } else {
      echo "The path is not a directory.";
   }
?>

輸出

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

The path is a directory.

示例

此 PHP 示例將執行操作以使用 is_dir() 函式檢查路徑是目錄還是檔案。

<?php
   //mention your path here
   $path = '/var/www/html/index.php';

   // Check if the given path is directory or file
   if (is_dir($path)) {
      echo "The path is a directory.";
   } else {
      echo "The path is not a directory.";
   }
?> 

輸出

這將產生以下結果:

The path is not a directory.

示例

在此 PHP 程式碼中,我們將使用 is_dir() 函式和相對路徑。因此,如果提到的路徑是相對路徑,則它將返回 true,否則返回 false。

<?php
   // Mention the relative path here
   $relativePath = './uploads';

   if (is_dir($relativePath)) {
       echo "The relative path is a directory.";
   } else {
       echo "The relative path is not a directory.";
   }
?> 

輸出

這將生成以下結果:

The relative path is a directory.

示例

在此 PHP 程式碼中,我們將使用 is_dir() 函式檢查陣列 $paths 中給出的多個路徑。因此,它將檢查給定的路徑是目錄還是檔案。

<?php
   // Mention multiple paths here
   $paths = ['/var/www/html', '/var/www/html/uploads', '/var/www/html/file.txt'];

   foreach ($paths as $path) {
      if (is_dir($path)) {
         echo "The path '$path' is a directory.\n";
      } else {
         echo "The path '$path' is not a directory.\n";
      }
   }

?> 

輸出

這將產生以下輸出:

The path '/var/www/html' is a directory.
The path '/var/www/html/uploads' is a directory.
The path '/var/www/html/file.txt' is not a directory.

注意

  • 驗證以確保路徑正確且易於查詢。
  • 當您需要在執行特定檔案操作(例如讀取或寫入檔案)之前確保目錄存在時,此函式很有用。

總結

is_dir() 函式是用於檢查給定路徑在 PHP 中是否為目錄的強大函式。此方法可用於在執行檔案操作之前驗證目錄是否存在。

php_function_reference.htm
廣告