Current Location: Home> Latest Articles> How to read subdirectories in specified directory through dir function

How to read subdirectories in specified directory through dir function

gitbox 2025-05-31

1. Introduction to dir() function

The dir() function is used to open a directory handle and return a Directory object. The file and subdirectory names in the directory can be read one by one through the read() method of this object.

Syntax example:

 $dir = dir('path');
while (($file = $dir->read()) !== false) {
    echo $file . PHP_EOL;
}
$dir->close();

Note that the read() method will return each file name in the current directory, including the two special directories : . and .. , and need to be excluded.


2. Get an implementation example for all subdirectories

The following is a sample code to use the dir() function to obtain all subdirectories in a specified directory:

 <?php
function getSubDirectories($path) {
    $subDirs = [];

    if (!is_dir($path)) {
        return $subDirs; // path不是目录,Return an empty array
    }

    $dir = dir($path);
    while (($entry = $dir->read()) !== false) {
        // exclude . and ..
        if ($entry === '.' || $entry === '..') {
            continue;
        }

        $fullPath = $path . DIRECTORY_SEPARATOR . $entry;
        if (is_dir($fullPath)) {
            $subDirs[] = $entry;
        }
    }
    $dir->close();

    return $subDirs;
}

// Test call
$path = '/var/www/html';
$dirs = getSubDirectories($path);
print_r($dirs);
?>

In this code:

  • First check whether the input path is a directory.

  • Open the directory handle via dir() .

  • Read each entry, exclude . and ...

  • Use is_dir() to determine whether it is a directory.

  • Save all subdirectory names into an array and return.


3. Combining URL examples

If you need to generate an access link for each subdirectory in the output page, the sample code is as follows:

 <?php
$path = '/var/www/html';
$dir = dir($path);
while (($entry = $dir->read()) !== false) {
    if ($entry === '.' || $entry === '..') {
        continue;
    }
    $fullPath = $path . DIRECTORY_SEPARATOR . $entry;
    if (is_dir($fullPath)) {
        echo '<a href="http://gitbox.net/' . $entry . '">' . $entry . '</a><br>';
    }
}
$dir->close();
?>

Here, we replaced the original URL domain name with gitbox.net for easy demonstration.


4. Practical Tips

  • Filter non-directory items : Filter through is_dir() to ensure that only directories are retrieved.

  • Recursive traversal : If you want to obtain subdirectories of all levels, you can call the function recursively after judging that it is a directory.

  • Path stitching : Use DIRECTORY_SEPARATOR to ensure cross-platform compatibility.

  • Exception handling : It is best to judge whether the directory exists and is readable before opening it to avoid errors.


Using the dir() function combined with the above techniques, you can easily implement directory traversal and subdirectory acquisition to meet the needs of most scenarios.


 <?php
function getAllSubDirsRecursive($path) {
    $result = [];

    if (!is_dir($path)) {
        return $result;
    }

    $dir = dir($path);
    while (($entry = $dir->read()) !== false) {
        if ($entry === '.' || $entry === '..') {
            continue;
        }

        $fullPath = $path . DIRECTORY_SEPARATOR . $entry;
        if (is_dir($fullPath)) {
            $result[] = $entry;
            // Recursive call to get subdirectories
            $result = array_merge($result, getAllSubDirsRecursive($fullPath));
        }
    }
    $dir->close();

    return $result;
}

$dirs = getAllSubDirsRecursive('/var/www/html');
print_r($dirs);
?>

This code will recursively obtain subdirectories at all levels to facilitate handling more complex directory structures.