Retrieve Directories, Subdirectories and Files with PHP

This article explains how to use PHP to retrieve directories, subdirectories, and files from a file system. Learn how to traverse through a directory tree.

Here's an example PHP code to retrieve directories, subdirectories, and files within a given directory:

 <?php

function get_files($dir, &$results = array()) {
    $files = scandir($dir);

    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if (!is_dir($path)) {
            $results[] = $path;
        } else if ($value != "." && $value != "..") {
            get_files($path, $results);
            $results[] = $path;
        }
    }

    return $results;
}

$dir = "path/to/directory";
$files = get_files($dir);

foreach ($files as $file) {
    echo $file . "<br />";
}

?>

Result:

../demo2/css/jquery.dataTables.css
../demo2/employee-grid-data.php
../demo2/employee.sql
../demo2/images/back_disabled.png
../demo2/images/back_enabled.png
../demo2/images/back_enabled_hover.png
../demo2/images/favicon.ico
../demo2/images/forward_disabled.png
../demo2/images/forward_enabled.png
../demo2/images/forward_enabled_hover.png
../demo2/images/sort_asc.png
../demo2/images/sort_asc_disabled.png
../demo2/images/sort_both.png
../demo2/images/sort_desc.png
../demo2/images/sort_desc_disabled.png
../demo2/images/Sorting icons.psd
../demo2/index.php
../demo2/js/jquery.dataTables.js
../demo2/js/jquery.js


In the code above, the "get_files" function uses the "scandir" function to retrieve the contents of the directory and iterates over the files and subdirectories. If a subdirectory is found, the function calls itself recursively to retrieve the files within the subdirectory. Finally, the function returns an array of all the files within the given directory.

To use this code, replace "path/to/directory" with the actual path to the directory you want to retrieve the files from, and then execute the code. The code will output the full path of all files within the directory and its subdirectories.

Please note that this code may not be suitable for all scenarios, and you should exercise caution when retrieving files from a directory. It is also recommended that you test any changes thoroughly before making them live on your website.