I am trying to get a list with folders and sub folders i have the following that allows me to get the folders and sub folders but i needed it to be sorted out like the e.g below i have been trying but i dont know how i would get around.
Root/
Root/Images
Root/Images/UserImages
Root/Text/
Root/Text/User1/
Root/Text/User1/Folder2
but at the 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("../");
Thank you
PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.
If you name one or more directories on the command line, ls will list each one. The -R (uppercase R) option lists all subdirectories, recursively. That shows you the whole directory tree starting at the current directory (or the directories you name on the command line).
The scandir() function returns an array of files and directories of the specified directory.
Collect the directory names in an array instead of echo
ing them directly. Use sort
on the array and a foreach
-loop to print the list.
So instead of echo ("$dirname/");
you would use $dirnames[] = $dirname;
(make $dirnames global and initialize it before your first call of "ListFolder"). Then after the recursive run of "ListFolder", you'd execute sort($dirnames);
and then something like this for the output:
foreach ($dirnames as $dirname)
{
echo $dirname . '<br />';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With