How to List All Files of the Root Directory and its Subdirectories Using PHP

PHP



In this article, we show how to list all files the root directory and all the directories on the root directory (its subdirectories) using PHP.

Every website has a home or root directory. This directory almost always contains other directories, which are subdirectories of this root directory.

What we want to do is be able to show all files in the root directory and all files in the subdirectories of the root directory.

So this includes all files in the root directory as well as all subdirectories of the home directory. This may includes the Articles (Articles/) directory, Documents (Documents/) directory, images (images/) directory, and so on and so forth. It shows all files in all directories in the root directory.

The code to show all files in the root directory and all files in the subdirectories using PHP is shown below.



So this PHP code above shows all the files in the root directory as well as all files in all directories in the root directory.

We'll now break down the code.

So we set the $directory variable equal to ".". This makes the directory selected the home (or root directory) which is the first and chief directory of any website.

We then use the PHP opendir() function to open up this root directory so that we have access to it.

We then use a while loop to loop through all the files in the directory. If any files are directories, the code advances.

We then open up these directories again using the opendir() function. We loop all all files in each of these directories. If the files aren't directories, we echo out the file.

And this is all that is required.

This, again, returns all files in the root directory as well as all files in the every directory on the root directory.

If you have subdirectories inside of subdirectories inside of subdirectories, this is a lot more complicated and difficult to achieve. It's obviously definitely achieveable.

But this code that I wrote about covers the case of returning all files in the root directory and each subdirectory of the root directory.



HTML Comment Box is loading comments...