Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to display folders and sub folders from dir in PHP

Tags:

directory

php

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

like image 975
Rickstar Avatar asked Nov 17 '10 13:11

Rickstar


People also ask

How can I get a list of all the subfolders and files present in a directory using PHP?

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.

How do I list sub folders?

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).

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.


1 Answers

Collect the directory names in an array instead of echoing 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 />';
}
like image 153
Select0r Avatar answered Oct 06 '22 01:10

Select0r