How to display folders and subfolders from dir in PHP

I'm trying to get a list with folders and subfolders, I have the following, which allows me to get folders and auxiliary folders, but I needed to sort it, like the ones below, which I tried, but I don’t know how I would get around .

Root/ Root/Images Root/Images/UserImages Root/Text/ Root/Text/User1/ Root/Text/User1/Folder2 

but on monent its display like this

 Root/css/ tree/css/ js/ images/ 

PHP CODE:

  function ListFolder($path) { $dir_handle = @opendir($path) or die("Unable to open $path"); //Leave only the lastest folder name $dirname = end(explode("/", $path)); //display the target folder. echo ("$dirname/"); while (false !== ($file = readdir($dir_handle))) { if($file!="." && $file!="..") { if (is_dir($path."/".$file)) { //Display a list of sub folders. ListFolder($path."/".$file); echo "<br>"; } } } //closing the directory closedir($dir_handle); } ListFolder("../"); 

thanks

+5
source share
3 answers

Collect the directory names in an array instead of echo directly. Use sort in the array and foreach -loop to print the list.

So, instead of echo ("$dirname/"); you must use $dirnames[] = $dirname; (make $ dirnames global and initialize it before the first call to "ListFolder"). Then, after starting the ListFolder recursively, you must do sort($dirnames); and then something like this to output:

 foreach ($dirnames as $dirname) { echo $dirname . '<br />'; } 
+3
source

you can get what you want using DirectoryIterator or better RecursiveDirectoryIterator from php SPL.

here is a brief example of how to use it:

  $dir = '/path/to/directory'; $result = array(); if (is_dir($dir)) { $iterator = new RecursiveDirectoryIterator($dir); foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) { if (!$file->isFile()) { $result[] = 'path: ' . $file->getPath(). ', filename: ' . $file->getFilename(); } } } 

That should do the trick. Good luck;)

+1
source

with this code you get lists with subdirectories (but set the folder name)

 <?php $path = realpath('yourfolder/examplefolder'); foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename) { echo "$filename\n"; } ?> 
+1
source

All Articles