Home  >  Q&A  >  body text

List all folders subfolders and files in a directory using php

<p>Please give me a solution to list all folders, subfolders, files in a directory using php. My folder structure is like this: </p> <pre class="brush:php;toolbar:false;">Main Dir Dir1 SubDir1 File1 File2 SubDir2 File3 File4 Dir2 SubDir3 File5 File6 SubDir4 File7 File8</pre> <p>I want to get a list of all files within each folder. </p> <p><strong>Is there a shell script command in php? </strong></p>
P粉891237912P粉891237912389 days ago472

reply all(2)I'll reply

  • P粉738346380

    P粉7383463802023-08-28 10:34:42

    A very simple way to display the folder structure is to use the RecursiveTreeIterator class (PHP 5 >= 5.3.0, PHP 7) and generate an ASCII graphical tree.

    $it = new RecursiveTreeIterator(new RecursiveDirectoryIterator("/path/to/dir", RecursiveDirectoryIterator::SKIP_DOTS));
    foreach($it as $path) {
      echo $path."<br>";
    }

    http://php.net/manual/en/class.recursivetreeiterator.php< /a>

    You can also have some control over the ASCII representation of the tree by changing the prefix using RecursiveTreeIterator::setPrefixPart, such as $it->setPrefixPart(RecursiveTreeIterator::PREFIX_LEFT, "| ");

    reply
    0
  • P粉482108310

    P粉4821083102023-08-28 00:51:33

    function listFolderFiles($dir){
        $ffs = scandir($dir);
    
        unset($ffs[array_search('.', $ffs, true)]);
        unset($ffs[array_search('..', $ffs, true)]);
    
        // prevent empty ordered elements
        if (count($ffs) < 1)
            return;
    
        echo '<ol>';
        foreach($ffs as $ff){
            echo '<li>'.$ff;
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            echo '</li>';
        }
        echo '</ol>';
    }
    
    listFolderFiles('Main Dir');
    

    reply
    0
  • Cancelreply