List all folders subfolders and files in a directory using php
P粉891237912
P粉891237912 2023-08-27 16:21:06
0
2
610
<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粉891237912
P粉891237912

reply all(2)
P粉738346380

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

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, "| ");

P粉482108310
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');
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template