- PHP: File Listing Class
- Basic usage
- The FileList class
- Enabling Recursion
- Supported key values
- Related Articles — Directory Listing
- User Comments
- Saved searches
- Use saved searches to filter your results more quickly
- halgatewood/file-directory-list
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- 4 Ways To List Files & Folders In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP GET FILES FOLDERS
- METHOD 1) SCANDIR
- 1A) BASIC SCANDIR
- 1B) SCANDIR READ SUB-FOLDERS
- METHOD 2) GLOB
- 2A) BASIC GLOB
- 2B) GLOB READ SUB-FOLDERS
- METHOD 3) OPENDIR
- 3A) BASIC OPENDIR
- 3B) OPENDIR READ SUB-FOLDERS
- METHOD 4) DIRECTORY ITERATOR
- 4A) BASIC ITERATOR
- 4B) ITERATOR READ SUB-FOLDERS
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- EXTRA) COMBINING GLOB & ITERATOR
- LINKS & REFERENCES
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
PHP: File Listing Class
This PHP class builds on our earlier directory listing functions and examples. The class is small and simple allowing us to extract specific file information from a single directory, or by recursing through a directory tree.
Basic usage
Our FileList PHP class comes with the following public methods:
void set_keys( . $keys ); specify which values to return for each file void add_filter( $key, Array ); return only files where $key matches one of the Array values void recurse(); or recurse( $depth ); whether to recurse, and how far array scan( $directory ); scan $directory returning an array of file details
For example, if we want to find all the XML and PDF files in the files/ directory, we use:
This populates the $files array with details of any matching files:
Array ( [0] => Array ( [mime_type] => application/xml [type] => file [pathname] => files/ajax1.xml [size] => 155 ) [1] => Array ( [mime_type] => application/xml [type] => file [pathname] => files/ajax2.xml [size] => 190 ) )
The list of support $key values is given below.
The FileList class
As you can see most of the work is done by the DirectoryIterator SPL class which returns a list (iterator) of SplFileInfo objects which we can query as we want.
For each file encountered we first check the filters values, and then the keys values. The array returned for each file will include all values specified in either list.
Coding-wise, the most interesting feature is the new . token which indicates a variable-length argument list. This is only available in PHP5.6+ and in earlier versions would need to be replaced by either an Array or a call to func_get_args.
Enabling Recursion
By default the FileList class will scan only a single directory, but enabling recursion is as simple as:
$filelist = new \Chirp\FileList(); $filelist->recurse();
Or, if you only want to go down one directory level:
$filelist = new \Chirp\FileList(); $filelist->recurse(1);
For example, to recursively search for PDF files by mime type:
Where . represents the current working directory.
Supported key values
The version of the class presented above supports the following keys:
‘basename’ file name without suffix ‘ext’ file name suffix ‘filename’ file name with suffix ‘imagesize’ array returned by getimagesize ‘mime_type’ file mime type as returned by mime_content_type ‘mtime’ last modified time ‘path’ relative directory path ‘pathname’ relative file path ‘realpath’ full path to the file ‘size’ file size in bytes ‘type’ dir, file or link
You can add support for more values by extending the extract method. There are a few generic SplFileInfo methods we’ve left out for brevity, and you may have other requirements.
Related Articles — Directory Listing
User Comments
One thing I found, in php 7.4: your
case ‘mime_type’:
return mime_content_type($finfo->getRealpath());
Was giving me an error.
may need to be:
case ‘mime_type’:
return $finfo->getRealpath();
I am upgrading my server to use PHP 7.4
It seems to be having an issue with the backslash in the \ Chirp \ FileList(
Any suggestions? It’s odd, because I use 7.4 on my local machine, and it gives me no issues. I did try to upgrade to PHP 8 and got similar error messages
Good and useful class — much appreciated!
There seems to be just one small problem. very large files may return incorrect (negative) file size values. Any idea?
Unfortunately this is a known bug with PHP not properly supporting files larger than 2Gb
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Free Super Clean PHP File Directory Listing Script
halgatewood/file-directory-list
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Free Super Clean PHP File Directory Listing Script
Easily display files and folders in a mobile friendly, clean and cool way. Just drop the index.php in your folder and you are ready to go. Past versions of this script can be found here: https://halgatewood.com/free/file-directory-list/
At the top of the index.php file you have a few settings you can change:
This will be the title of your page and also is set to the meta mitle of the document.
Change this variable to dark when you are feeling down.
— $ignore_file_list = array( «.htaccess», «Thumbs.db», «.DS_Store», «index.php» );
Create an array of files that you do not want to appear in the listing
You can create an array of extensions not to show, for example: ‘jpg,png,gif,pdf’
This will sort the files, the available options are: name_asc, name_desc, date_asc, date_desc
A data sprite of evenly spaced out icons. You can create your own like the one found here: https://www.dropbox.com/s/lzxi5abx2gaj84q/flat.png?dl=0
If a folder is clicked on, it will slide down the sub folder. You can turn this off here.
This will add the html download attribute which forces the download in some browsers.
Ability to hide empty folders.
4 Ways To List Files & Folders In PHP (Simple Examples)
Welcome to a tutorial on how to list files and folders in PHP. So you need to get the contents of a folder in PHP? Well, be prepared for a small nasty surprise.
- foreach (scandir(«FOLDER») as $ff) < . >
- foreach (glob(«FOLDER/*») as $ff) < . >
- Open and read the folder.
- $dh = opendir(«FOLDER»);
- while ($ff = readdir($dh))
- Use an iterator.
- $it = new DirectoryIterator(«FOLDER»);
- foreach ($it as $ff)
That covers the basics, but just what is the difference? Read on for more examples!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP GET FILES FOLDERS
All right, let us now get into the examples of getting files and folders in PHP.
METHOD 1) SCANDIR
1A) BASIC SCANDIR
- file "; > if (is_dir($dir . $ff)) < echo "- folder "; > >
- scandir(«FOLDER») will give you the full list of files and folders within the specified folder in an array.
- Take note, this also includes the hidden . and .. . For those who are new, these represent the current and parent folder respectively.
- We are not interested in the “dots”, so we remove them using array_diff() .
- The rest is self-explanatory – Loop through the files and folders.
1B) SCANDIR READ SUB-FOLDERS
- file "; > if (is_dir($dir . $ff)) < echo "- folder "; rscan("$dir$ff/"); > > > // (B) GO! rscan("YOUR/FOLDER/");
If you need to “dig” into the sub-folders, create a recursive function – If the entry is a folder, pass it back into the recursive function itself.
METHOD 2) GLOB
2A) BASIC GLOB
// (A) GET FILES/FOLDERS $all = glob("YOUR/FOLDER/*"); // $all = glob("YOUR/FOLDER/*.", GLOB_BRACE); $eol = PHP_EOL; // (B) LOOP THROUGH ALL foreach ($all as $ff) < if (is_file($ff)) < echo "- file "; > if (is_dir($ff)) < echo "- folder "; > >
Now, scandir() will fetch everything. If you only need certain file types – glob() is the best option.
2B) GLOB READ SUB-FOLDERS
// (A) RECURSIVE GLOB function rglob ($dir, $ext="*") < // (A1) GET FILES $eol = PHP_EOL; foreach (glob("$dir$ext", GLOB_BRACE) as $ff) < if (is_file($ff)) < echo "- file "; > > // (A2) GET FOLDERS foreach (glob("$dir*", GLOB_ONLYDIR | GLOB_MARK) as $ff) < echo "- folder "; rglob($ff, $ext); > > // (B) GO! rglob("YOUR/FOLDER/"); // rglob("YOUR/FOLDER/", "*.");
A “recursive glob” is slightly more roundabout, but basically – Get the files first, then recursive “dig” into the folder.
METHOD 3) OPENDIR
3A) BASIC OPENDIR
- file "; > if (is_dir($ff)) < echo "- folder "; > >>
The above methods will “fetch everything into an array”. Some of you sharp code ninjas should have already caught the potential problem – What if there are thousands of files in the folder? This will run into performance and memory issues. So instead of “getting everything at once”, opendir() and readdir() will read “entry by entry”.
3B) OPENDIR READ SUB-FOLDERS
- file "; > if (is_dir($ff)) < echo "- folder "; rread("$ff/"); > >> > // (B) GO! rread("YOUR/FOLDER/");
Well, this should not be a surprise by now. Create a recursive function to open and read sub-folders.
METHOD 4) DIRECTORY ITERATOR
4A) BASIC ITERATOR
isDot()) < continue; >if ($ff->isFile()) < echo "getFilename()> - file "; > if ($ff->isDir()) < echo "getFilename()> - folder "; > >
Lastly, here is the “alternative” way to read a folder entry by entry – Using a DirectoryIterator .
4B) ITERATOR READ SUB-FOLDERS
isDot()) < continue; >if ($ff->isFile()) < echo "getFilename()> - file "; > if ($ff->isDir()) < echo "getFilename()> - folder "; riterate("getFilename()>/"); > > > // (B) GO! riterate("YOUR/FOLDER/");
Well… You guys should be masters of recursive functions by now.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
EXTRA) COMBINING GLOB & ITERATOR
// (A) GLOB ITERATOR $dir = "D:/DOCS/"; $eol = PHP_EOL; // $iterator = new ArrayObject(glob("$dir*.", GLOB_BRACE)); $iterator = new ArrayObject(glob("$dir*", GLOB_BRACE)); $iterator = $iterator->getIterator(); /* (B) OPTIONAL - PAGINATION $pgNow = 0; // current page $pgPage = 10; // entries per page $iterator = new LimitIterator($iterator, $pgNow * $pgPer, $pgPer); */ // (C) LOOP foreach ($iterator as $ff) < if (is_file($ff)) < echo "- file "; > if (is_dir($ff)) < echo "- folder "; > >
Which is the “best method”? I will say “all of them”, whichever works for you is the best. But personally, my “best solution” is a combination of glob and iterator – This is very flexible, capable of restricting by the file types, and also easily do pagination with it.
LINKS & REFERENCES
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!