In this article, we will see how to list directories, subdirectories, and files using PHP.

To achieve this we use some of the inbuilt functions such as opendir(), readdir(), is_dir(), and closedir().

Following is an example program on how to list directories, subdirectories and files using php.

<?php
function listFilesAndDirectories($directoryPath) {
    $dirHandle = opendir($directoryPath);
    if (!$dirHandle) {
        return [];
    }

    $entries = [];
    while (($entry = readdir($dirHandle)) !== false) {
        if ($entry === '.' || $entry === '..') {
            continue;
        }

        $entryPath = $directoryPath . '/' . $entry;

        if (is_dir($entryPath)) {
            $subEntries = listFilesAndDirectories($entryPath);
            $entries = array_merge($entries, $subEntries);
        } else {
            $entries[] = $entryPath;
        }
    }

    closedir($dirHandle);
    return $entries;
}

$directoryPath = 'path/to/your/directory';
$entries = listFilesAndDirectories($directoryPath);
echo "Contents of $directoryPath:\n";

foreach ($entries as $entry) {
   echo $entry . "\n";
}

?>

Explanation:

Let’s define a function called listFilesAndDirectories which accepts the directory path in which we want to list directories and subdirectories.

We use the opendir() function to open the specified directory. In case, if the directory cannot be opened, we return an empty array.

After that,

We used a while loop and the readdir() function to iterate through the entries in the directory. Please note, here we have to skip the current directory '.' and the parent directory '..' entries.

is_dir() function is used to to check if the current entry is a directory or not. If it is a directory, call the listFilesAndDirectories function recursively to list its contents of that directory.

After processing all the entries, use the closedir() function to close the directory and return the data.

Categorized in:

Tagged in: