How to get names of all the subfolders and files present in a directory using PHP?

Given the path of the folder and the task is to print names of subfolders and files present inside them.

Explaination: In our PHP code, initially, it is checked whether provided path or filename is a directory or not using is_dir() function. Now, we open the directory using opendir() function and then checking whether it is getting opened or have some errors. Then we use a while loop to get names of all the subfolders, as well as files, present inside the directory with the help of readdir() function. Now we are going inside each subfolder and reading the names of all the files present inside them following a similar procedure.

Folder Structure:

Code:
Note: This Code have been saved as PHP file and accessed through wampserver

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
$gfg_folderpath = "GeeksForGeeks/";
// CHECKING WHETHER PATH IS A DIRECTORY OR NOT
if (is_dir($gfg_folderpath)) {
    // GETING INTO DIRECTORY
    $files = opendir($gfg_folderpath); {
        // CHECKING FOR SMOOTH OPENING OF DIRECTORY
        if ($files) {
            //READING NAMES OF EACH ELEMENT INSIDE THE DIRECTORY 
            while (($gfg_subfolder = readdir($files)) !== FALSE) {
                // CHECKING FOR FILENAME ERRORS
             if ($gfg_subfolder != '.' && $gfg_subfolder != '..') {
                    echo "SUBFOLDER--" .$gfg_subfolder . "<br>
                    "."Files in ".$gfg_subfolder."--<br>";
                      
                $dirpath = "GeeksForGeeks/" . $gfg_subfolder . "/";
                    // GETING INSIDE EACH SUBFOLDERS
                    if (is_dir($dirpath)) {
                        $file = opendir($dirpath); {
                            if ($file) {
                //READING NAMES OF EACH FILE INSIDE SUBFOLDERS
               while (($gfg_filename = readdir($file)) !== FALSE) {
                if ($gfg_filename != '.' && $gfg_filename != '..') {
                        echo $gfg_filename . "<br>";
                           }
                         }
                      }
                   }
               }
                    echo "<br>";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>What's there in GeeksForGeeks </title>
</head>
<body>
</body>
</html>

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.