How to go through a directory recursively returning the full path in PHP?

I am trying to get behavior like the "tree" command on Linux or Unix systems where the function returns a list or array of directories in its full path.

Example

~/
~/Pictures
~/Movies
~/Downloads
~/Documents
~/Documents/work
~/Documents/important
~/Documents/bills
~/Music
~/Music/80s/

etc. etc....

+3
source share
2 answers
foreach (new RecursiveIteratorIterator (new RecursiveDirectoryIterator ('.')) as $x)
{
        echo $x->getPathname (), "\n";
}

Update # 1:

If you want to also specify empty directories, use RecursiveIteratorIterator :: CHILD_FIRST

foreach (new RecursiveIteratorIterator (new RecursiveDirectoryIterator ('.'), RecursiveIteratorIterator::CHILD_FIRST) as $x)
{
    echo $x->getPathname (), "\n";
}
+7
source

Checkout PHP Recursivedirectoryiterator . He will do what you need and he has interesting examples.

+1
source

All Articles