How to List All the Directories of a Website Using PHP
In this article, we show how to list all directories of a website using PHP.
How this is done is not that simple. It depends on the amount of subdirectories you have.
For example, every directory has a home or root directory. This directory almost always contains other directories, which are subdirectories of this home directory.
If you just want to show all of the directories in this home directory, the PHP code to do is.
This PHP code above shows all the directories that are in the root directory (the subdirectories of 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 home 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, we then echo out this directory.
How we know if any files are directories is through the PHP is_dir() function. This function checks to see if any files in the root directory are directories.
So all is good with this code if you only have 1 set of subdirectories on your website. This may be an Articles (Articles/) directory, Documents (Documents/) directory, images (images/) directory.
But now what if you have another set of subdirectories in these directories. For example, in the Articles directory, you may have an images directory. In the Documents directory, you may have a PDFs directory. And so on and so forth.
So now we're dealing with 2 levels of subdirectories.
How can use PHP code to now get every directory on the website?
It's a little more complicated but the code to do this is shown below.
This code now shows all directories of the home directory, all the directories on the home directory, and all of the first set of subdirectories in the directories of the home directory.
So now the code will show subdirectories in the directories on the home directory.
For example, now it will show the images directory in the Articles directory (Articles/images/). It will show the PDFs directory in the Documents directory (Documents/PDFs/).
This code goes another layer deep into the directories on a website.
But if your website has even more subdirectories inside of directories, you just have to amend the code so it can keep showing more and more subdirectories that matches deep your site goes into it.
Being that PHP has no explicit function to find all directories on your website, you have to build the code necessary to show these directories. So based on your site, you custom build the code based on the layers of subdirectories that you have.
But unless your site is very complex, either one of these scripts should suffice.