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:


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 />";



../demo2/images/Sorting icons.psd

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.