Hacker
Hacker

Reputation: 7906

Print all files and folders in a folder recursively

I want to list all files and folders in a folder recursively. I have written code to get the output, but i am not able to show in a proper nested manner.

   <?php


class CheckFolder{

    public function getSubFolders($dir)
    {
        $folders = array();
        $ffs = scandir($dir);
        foreach($ffs as $ff)
        {
            if($ff != '.' && $ff != '..')
            {
                if(is_dir($dir.'/'.$ff))  $folders[] = $ff;
            }
        }
        return $folders;      
    }

    public function getFiles($dir)
    {
        $files = array();
        if(is_dir($dir))
        {
            $ffs = scandir($dir);
            foreach($ffs as $ff)
            {
                if($ff != '.' && $ff != '..')
                {
                    if(!is_dir($dir.'/'.$ff))  $files[] = '<li>'.$ff.'</li>';
                }
            }
        }
        return $files;
    }    

    function listFolderFiles($dir)
    {
        $ffs     = scandir($dir);
        $folders = $this->getSubFolders($dir);
        $files   = $this->getFiles($dir);

        if(strpos($dir, '/') >0)
        {
            $folderName = substr($dir, strrpos($dir, '/') + 1);
        }
        else
        {        
            $folderName =   $dir;
        }
        echo '<ul>';
        echo '<li>'.$folderName.'</li>';
        if(count($files) > 0)
        {   
            echo '<ul>';
            foreach($files as $file)
            {
                // /echo '<li>'.$file.'</li>';
                echo $file;
            }
            echo '</ul>';
        }

        echo '</ul>';

        foreach($folders as $folder)
        {
           // echo '<li>'.$folderName.'</li>';
            $this->listFolderFiles($dir.'/'.$folder); 
        }

    }


}

$dir = 'test';
$folder = new CheckFolder();
$folder->listFolderFiles($dir)

?>

Current Output enter image description here

Expected:

enter image description here

Upvotes: 0

Views: 528

Answers (1)

Professor Abronsius
Professor Abronsius

Reputation: 33813

I don't know if you have looked at, and possibly discounted, the built in recursiveIterator and recursiveDirectoryIterator set of classes?

The below does not take care of the indentation to which you refer but it is a great way ( although perhaps not as quick as a recursive function of your own making ) to iterate through all directories in a path.

The manual is sparse with good examples IMHO but the following might be of interest, especially as you can specify things like CHILD_FIRST.

$folder=__DIR__;
foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $folder, RecursiveDirectoryIterator::KEY_AS_PATHNAME ), RecursiveIteratorIterator::CHILD_FIRST ) as $file => $info ) {
    if( $info->isFile() && $info->isReadable() && $info->isWritable() ){
        echo $info->getPathname() .' ' . $info->getFilename().BR;
    }
}

Upvotes: 2

Related Questions