The Wayback Machine - https://web.archive.org/web/20240928123502/https://www.geeksforgeeks.org/how-to-get-names-of-all-the-subfolders-and-files-present-in-a-directory-using-php/
Open In App

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

Last Updated : 19 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 



Previous Article
Next Article

Similar Reads

Copy the entire contents of a directory to another directory in PHP
Given a directory and the task is to copy the content of the directory to another directory using PHP functions. There are many functions used to copy the content of one directory to another. Used Functions: copy() Function: The copy() function is used to make a copy of a specified file. It makes a copy of the source file to the destination file an
3 min read
How to include() all PHP files from a directory ?
Given list of PHP files in a directory and the task is to include all files from a directory. In order to include all PHP files from directory at once need a foreach-loop. Example: This example contains four PHP files (file1.php, file2.php, file3.php, file4.php) in a directory. Create one file named as main.php which contains PHP code to include fi
1 min read
How to count files in a directory using PHP?
PHP contains many functions like count(), iterator_count(), glob(), openddir(), readdir(), scandir() and FilesystemIterator() to count number of files in a directory.count() Function: The count() functions is an array function which is used to count all elements in an array or something in an object. This function uses COUNT_RECURSIVE as a mode to
3 min read
How to recursively delete a directory and its entire contents (files + sub dirs) in PHP?
In PHP if you want to delete the file or directory then keep one thing in mind that you cannot delete the file or directory directly there is a condition on that i.e. there are some security issues are there so the best way to do this is you first have to delete the data present in the file or the sub files or directories present in it . Then only
3 min read
How to display all files in a directory using Node.js ?
The files present in a directory can be displayed using two approaches in Node.js that are discussed below: Method 1: Using fs.readdirSync() method: The fs.readdirSync() is a method that is available in the file system module of Node.js. It is used for reading the contents of a directory. It returns an array of file paths, buffers, or fs.Dirent obj
3 min read
ASP SubFolders Collection
The ASP SubFolders Collection is used to return the collection of all the subfolder in a specified folder. Syntax: FolderObject.SubFolders Example: The below code demonstrates the ASP Folder.SubFolders Collection. C/C++ Code <% dim fs,fo,x set fs=Server.CreateObject("Scripting.FileSystemObject") 'Get the folder to be read set fo=fs.Get
1 min read
How to get all function names of a module in PHP ?
In this article, we will learn How to get the names of all functions present in a module in PHP. What is a module in PHP ? A module is a collection of independent software components. The usage of modules in program improves the code reusability and encapsulation. Module contains functions that we can use these functions by including the module in
2 min read
PHP | dir() (Get instance of the Directory)
The dir() function in PHP used to find the instance of a Directory class. This function read directory, which includes the following: The given directory is opened. The two properties handle and path of dir() are available. The handle property can be used with other directory functions such as readdir(), rewinddir(), closedir(). The path property i
2 min read
How to keep compiled files in a separate directory ?
A web project containing HTML, CSS, JavaScript, Images, and Videos files. The task is to ensure that all the files of the project are compiled and bundled to one separate directly. Before we proceed, I would like to give you a brief introduction to parcel-bundler. Parcel-bundler: It is a module that helps to transcribe our ES6+ syntax into a tradit
4 min read
How to see the changes in whole directory/folder containing many sass files ?
SASS is a powerful preprocessing language that helps us to write our code more efficiently in an easy and concise manner. Some of the best features of sass are using variables, support nesting, and using functions. While it has many advantages, keeping track of all the changes in a sass file could seem like a complicated task. The easiest method to
2 min read
How To List Only The Names Of Files That Changed Between Two Commits?
Git is a powerful version control system that allows developers to track changes in their codebase. One common task is identifying which files have changed between two specific commits. This can be useful for code reviews, debugging, and understanding the impact of changes. In this article, we'll explore how to list only the names of files that cha
3 min read
How to get information of all collections present in MongoDB database using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Installing module: You can install mongodb module using
1 min read
How to get information of all databases present in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Installing module: You can install mongodb module using
1 min read
How to copy a file from one directory to another using PHP ?
The copy() function in PHP is used to copy a file from source to target or destination directory. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure. Syntax: bool copy( string $source, string $destination, resour
2 min read
How to get the current pathname in the app directory of Next.js?
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn about How to get the current pathname in the app directory of NextJS. Approach to get the current
3 min read
Deleting all files from a folder using PHP
In PHP, files from a folder can be deleted using various approaches and inbuilt methods such as unlink, DirectoryIterator and DirectoryRecursiveIterator. Some of these approaches are explained below: Approach 1: Generate a list of files using glob() method Iterate over the list of files. Check whether the name of files is valid. Delete the file usi
3 min read
How to create directory with HTML button and PHP ?
The mkdir() function is used to create directory in PHP. It is an inbuilt function in PHP. The mkdir() function creates a new directory with the specified pathname. The path and mode are sent as parameters to the mkdir() function and it returns TRUE on success or FALSE on failure. Syntax: mkdir( path, mode, recursive, context ) Return Value: This f
1 min read
How to get the elements of one array which are not present in another array using JavaScript?
The task is to get the elements of one array that are not present in another array. Here we are going to use JavaScript to achieve the goal. Here are a few techniques discussed. Approach Take the arrays in variables.Use the .filter() method on the first array and check if the elements of the first array are not present in the second array, Include
2 min read
How to get the javascript function parameter names/values dynamically ?
In this article, we are given any arbitrary JavaScript function and the task is to return the parameter names of the function. Approach: JavaScript contains a method called toString() which is used to represent a function code in its string representation. This method is used to get the parameter names/values. First, get the function's code to its
2 min read
How to get an array of function property names from own enumerable properties of an object in JavaScript ?
Enumerable Properties: All the properties of an object that can be iterated using for..in loop or Object.keys() method are known as enumerable properties. In this article, we will see how to get an array of functions of an object that are enumerable. It can be achieved by following these 2 steps. Using Object.keys() method, we can get an array of a
2 min read
How to Get Names of Enum Entries in TypeScript?
A TypeScript enum is a unique class that represents a collection of constants. In this article, we will learn how we can get the names of the entries of a TypeScript enum. There are many different ways of getting the names of enum entries as listed below: Table of Content By using the Object.keys() and Object.values()By using the for-in loopBy usin
3 min read
How to Zip a directory in PHP?
ZIP is an archive file format that supports lossless data compression. A ZIP file may contain one or more files or directories that may have been compressed. The PHP ZipArchive class can be used to zipping and unzipping. It might be need to install the class if it is not present. Installation for Linux users: In order to use these functions you mus
2 min read
Why PHP script does not create a directory with 777 permissions ?
In PHP, we aren't able to create a directory with 777 permission because of default umask. The umask is called a user mask or user file creation mask. This is a kind of base permission or default permission given when a new file or folder is created. The default value of umask is generally 022. The umask sets in which permissions must be removed fr
3 min read
How to select and upload multiple files with HTML and PHP, using HTTP POST?
In this article, we will look at how to upload multiple files with HTML and PHP. Multiple image upload allows the user to select multiple files at once and upload all files to the server. index.html Create a simple HTML page to select multiple files and submit it to upload files on the server. Here, the HTML file contains a form to select and uploa
3 min read
How to get meta data of files in firebase storage using ReactJS ?
Within the domain of web development, effective file management is a frequent necessity, and Firebase Storage emerges as a resilient solution. This article explores the nuances of extracting metadata from files housed in Firebase Storage through the lens of ReactJS. PrerequisitesNode JS or NPMReact JSFireBaseSteps to create React Application And In
2 min read
PHP Program to Sort Names in an Alphabetical Order
Sorting names in alphabetical order is a common task in programming. PHP provides several functions and methods to achieve this. Examples: Input: arr = ["Sourabh", "Anoop, "Harsh", "Alok", "Tanuj"]Output: ["Alok", "Anoop", "Harsh", "Sourabh", "Tanuj"]Input: arr = ["John", "Alice", "Bob", "Eve", "Charlie"] Output: ["Alice", "Bob", "Charlie", "Eve",
2 min read
How To Show All Remote And Local Branch Names?
Git is a powerful version control system that helps developers manage and track changes in their projects. Understanding how to list both remote and local branches is important for effective Git usage, especially when collaborating with a team. This article will guide you through the steps to display all remote and local branch names in Git. Table
3 min read
How to create a table in PDF file from external text files using PHP ?
In this article, we will learn to create a table in a PDF file from an external text file with PHP by using FPDF. It is a free PHP class that contains many functions for creating and modifying PDFs. The FPDF class includes many features like page formats, page headers, footers, automatic page break, line break, image support, colors, links, and man
3 min read
How to generate PDF file from external text files using PHP ?
In this article, we will learn how to generate PDF files from external text files with PHP by using FPDF. It is a free PHP class that contains many functions for creating and modifying PDFs. The FPDF class includes many features like page formats, page headers, footers, automatic page break, line break, image support, colors, links, and many more.
5 min read
How to open a PDF files in web browser using PHP?
Opening a PDF file in a web browser using PHP involves serving the PDF directly to the client’s browser. This is achieved by setting the appropriate HTTP headers (Content-Type and Content-Disposition) in PHP, which instructs the browser to display the PDF instead of downloading it. Note: PHP doesn't read PDFs but passes them to the browser. If stor
2 min read