Home > Article > Backend Development > How to Recursively List Directories and Files with PHP?
To list all folders, subfolders, and files within a given directory in PHP, you can employ the scandir() function. This powerful tool enables you to obtain a detailed snapshot of a directory's contents.
Consider the following directory structure as an example:
Main Dir Dir1 SubDir1 File1 File2 SubDir2 File3 File4 Dir2 SubDir3 File5 File6 SubDir4 File7 File8
To list all the files and subdirectories, you can utilize the following PHP code:
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');
This code recursively traverses the given directory, identifying all files and subdirectories. The resulting list will be presented in a nested, ordered HTML list (
By leveraging the scandir() function and the recursive approach showcased above, you can effectively obtain a comprehensive inventory of any directory's contents in PHP.
The above is the detailed content of How to Recursively List Directories and Files with PHP?. For more information, please follow other related articles on the PHP Chinese website!