Home >Backend Development >PHP Tutorial >How to Recursively List Files and Subdirectories in PHP?

How to Recursively List Files and Subdirectories in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-13 10:10:02693browse

How to Recursively List Files and Subdirectories in PHP?

Listing Files and Subdirectories Recursively in PHP

Listing all the subdirectories, files, and subfolders within a given directory can be a common task. In PHP, this can be achieved using the scandir() function.

Let's consider a scenario where you have the following directory structure:

<br>Main Dir<br> Dir1<br>  SubDir1<br>   File1<br>   File2<br>  SubDir2<br>   File3<br>   File4<br> Dir2<br>  SubDir3<br>   File5<br>   File6<br>  SubDir4<br>   File7<br>   File8<br>

Your objective is to retrieve a list of all the files contained within each folder.

Solution

PHP doesn't provide a direct equivalent to shell script commands like ls. However, you can implement recursive listing using a PHP function. Here's a sample code snippet:

function listFolderFiles($dir){
    $ffs = scandir($dir);

    unset($ffs[array_search('.', $ffs, true)]);
    unset($ffs[array_search('..', $ffs, true)]);

    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>';
}

Usage

Call the listFolderFiles() function with the directory path you want to process, as shown below:

listFolderFiles('Main Dir');

The function will output a hierarchically organized HTML list representing the directory structure, with files and subdirectories listed accordingly.

The above is the detailed content of How to Recursively List Files and Subdirectories in 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