Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

directory

php

I'm trying to get the 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...

like image 828
chutsu Avatar asked Dec 17 '25 16:12

chutsu


2 Answers

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

Update #1:

If you want empty directories to be listed as well, use RecursiveIteratorIterator::CHILD_FIRST

foreach (new RecursiveIteratorIterator (new RecursiveDirectoryIterator ('.'), RecursiveIteratorIterator::CHILD_FIRST) as $x)
{
    echo $x->getPathname (), "\n";
}
like image 169
akond Avatar answered Dec 20 '25 08:12

akond


Checkout PHP's Recursivedirectoryiterator. It will do what you need, and it has some nice examples.

like image 37
Wesley van Opdorp Avatar answered Dec 20 '25 07:12

Wesley van Opdorp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!