How to get names of all the subfolders and files present in a directory using PHP? Last Updated : 19 Apr, 2023 Comments Improve Suggest changes 3 Likes Like Report Given the path of the folder and the task is to print the names of subfolders and files present inside them. Explanation: In our PHP code, initially, it is checked whether provided path or filename is a directory or not using the is_dir() function. Now, we open the directory using opendir() function and then check whether it is getting opened or has some errors. Then we use a while loop to get the 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 php <?php $gfg_folderpath = "GeeksForGeeks/"; // CHECKING WHETHER PATH IS A DIRECTORY OR NOT if (is_dir($gfg_folderpath)) { // GETTING 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 . "/"; // GETTING 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> Output: Comment H hacksight Follow 3 Improve H hacksight Follow 3 Improve Article Tags : Web Technologies PHP PHP Programs PHP-file-handling Explore PHP Tutorial 8 min read BasicsPHP Syntax 4 min read PHP Variables 5 min read PHP | Functions 8 min read PHP Loops 4 min read ArrayPHP Arrays 5 min read PHP Associative Arrays 4 min read Multidimensional arrays in PHP 5 min read Sorting Arrays in PHP 4 min read OOPs & InterfacesPHP Classes 2 min read PHP | Constructors and Destructors 5 min read PHP Access Modifiers 4 min read Multiple Inheritance in PHP 4 min read MySQL DatabasePHP | MySQL Database Introduction 4 min read PHP Database connection 2 min read PHP | MySQL ( Creating Database ) 3 min read PHP | MySQL ( Creating Table ) 3 min read PHP AdvancePHP Superglobals 6 min read PHP | Regular Expressions 12 min read PHP Form Handling 4 min read PHP File Handling 4 min read PHP | Uploading File 3 min read PHP Cookies 9 min read PHP | Sessions 7 min read Like