Listing all the folders subfolders and files in a directory using php

A very simple way to show folder structure makes use of RecursiveTreeIterator class (PHP 5 >= 5.3.0, PHP 7) and generates an ASCII graphic tree.

$it = new RecursiveTreeIterator(new RecursiveDirectoryIterator("/path/to/dir", RecursiveDirectoryIterator::SKIP_DOTS));
foreach($it as $path) {
  echo $path."<br>";
}

http://php.net/manual/en/class.recursivetreeiterator.php

There is also some control over the ASCII representation of the tree by changing the prefixes using RecursiveTreeIterator::setPrefixPart, for example $it->setPrefixPart(RecursiveTreeIterator::PREFIX_LEFT, "|");


function listFolderFiles($dir){
    $ffs = scandir($dir);

    unset($ffs[array_search('.', $ffs, true)]);
    unset($ffs[array_search('..', $ffs, true)]);

    // prevent empty ordered elements
    if (count($ffs) < 1)
        return;

    echo '<ol>';
    foreach($ffs as $ff){
        echo '<li>'.$ff;
        if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
        echo '</li>';
    }
    echo '</ol>';
}

listFolderFiles('Main Dir');

Tags:

Php

Directory