PHP scandir() 函式



PHP 的 scandir() 函式用於獲取當前目錄或指定目錄中的所有檔案。此函式返回給定目錄中的檔案和目錄的陣列。

目錄、流行為和檔案和目錄的排序順序作為引數傳遞給 scandir() 函式,該函式在成功時返回檔名陣列,在失敗時返回 false。

預設情況下,排序順序為按字母順序升序。如果可選的 sorting_order 設定為 SCANDIR_SORT_DESCENDING,則排序順序為按字母順序降序。如果使用 SCANDIR_SORT_NONE,則結果為未排序。

語法

以下是 PHP Directory scandir() 函式的語法:

array scandir ( string $directory [, int $sorting_order [, resource $context]] );

引數

下面列出了使用 scandir() 函式所需的引數:

序號 引數及說明
1

directory(必需)

將要掃描的目錄。

2

sorting_order(可選)

指定排序順序。預設為 0(升序)。如果設定為 1,則表示降序。

3

context(可選)

指定目錄控制代碼的上下文。上下文是一組可以修改流行為的選項。

返回值

成功時返回檔名陣列,失敗時返回 FALSE。

PHP 版本

scandir() 函式在 PHP 4 核心版本中引入,並且與 PHP 5、PHP 7 和 PHP 8 相容。

示例

我們將使用 PHP Directory scandir() 函式列出指定目錄路徑中存在的所有檔案和目錄。

程式將按升序列印內容,然後按降序列印內容。

<?php
   $dir    = '/newfolder';
   $files1 = scandir($dir);
   $files2 = scandir($dir, 1);
   
   print_r($files1);
   print_r($files2);
?> 

輸出

這將產生以下結果:

Array (
   [0] => .
   [1] => ..
   [2] => abc.php
   [3] => bbc.txt
   [4] => somedir
)
Array (
   [0] => somedir
   [1] => indiabbc.txt
   [2] => status999.php
   [3] => ..
   [4] => .
)

示例

在下面的 PHP 程式碼中,我們將僅使用 scandir() 函式及其名為 SCANDIR_SORT_DESCENDING 的引數來按降序列出內容。

<?php
   $directory = "/Applications/XAMPP/xamppfiles/htdocs/mac";
   $contents = scandir($directory, SCANDIR_SORT_DESCENDING);

   foreach ($contents as $item) {
      echo $item . "<br>";
   }
?> 

輸出

這將產生以下結果:

new dir
myfile.txt
my.php
logo.gif
index.php
images
image.gif
.DS_Store
..
.

示例

在這裡,我們將使用 scandir() 函式掃描目錄,並藉助 is_dir() 函式驗證給定路徑中可用的目錄,並列印其名稱。

<?php
   // enter your working directory path here
   $directory = "/Applications/XAMPP/xamppfiles/htdocs/mac";

   // now scan the directory
   $items = scandir($directory);

   // print the directory here using foreach loop
   echo "Directories are: " . "<br>";
   foreach ($items as $item) {
      $dir = "$directory/$item";
      if (is_dir($dir)) {
         echo $item . "<br>";
      }
   }
?> 

輸出

這將導致以下結果:

Directories are:
.
..
images
new dir

示例

在下面的 PHP 程式碼中,我們將使用 scandir() 函式掃描目錄,並藉助 is_file() 函式驗證給定路徑中可用的檔案,並顯示其名稱。

<?php
   // enter your working directory path here
   $directory = "/Applications/XAMPP/xamppfiles/htdocs/mac";
   $items = scandir($directory);
   echo "Files are: " . "<br>";
   foreach ($items as $item) {
      $filePath = $directory . '/' . $item;
      if (is_file($filePath)) {
         echo $item . "<br>";
      }
   }
?> 

輸出

此 PHP 程式碼的結果為:

Files are:
.DS_Store
image.gif
index.php
logo.gif
my.php
myfile.txt

注意

  1. scandir() 返回當前目錄 (.) 和父目錄 (..)。
  2. 傳遞給 scandir() 的不正確的目錄路徑會生成 E_WARNING 錯誤並返回 FALSE。
  3. scandir() 是耗時的 readdir() 方法的較短替代方法,後者一次讀取一個目錄條目。
  4. 可以使用 is_file() 函式將目錄條目限制為僅檔案。
  5. 使用 is_dir() 函式將目錄與目錄條目分開。
  6. 使用 array_diff() 函式從結果陣列中刪除條目。

總結

PHP 中的 scandir() 函式可用於列出指定目錄內的檔案和目錄。它易於使用,並提供可變的結果排序。

php_function_reference.htm
廣告