Home  >  Article  >  Backend Development  >  How to Recursively List Directories and Files with PHP?

How to Recursively List Directories and Files with PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 08:03:09365browse

How to Recursively List Directories and Files with PHP?

Listing Directories Recursively 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 (

    ). Additionally, the code excludes the default "." and ".." entries that represent the current and parent directories, respectively.

    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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn