This article demonstrates how to list all files in a directory in PHP.

1. Using scandir() function

The standard solution to list all entries in the specified path is to use the scandir() function. The default sort order of the returned array by scandir() is ascending. To change the sorted order to descending, you can set the sorted_order parameter to SCANDIR_SORT_DESCENDING. If you don’t want to sort the results, consider setting it to SCANDIR_SORT_NONE.

 
Note that the returned array from scandir() contains all the files and subdirectories in a directory, including dots (. and ..). You can easily get rid of the directory entries . and .. using the array_slice() solution, as demonstrated below:

Download Code

2. Using readdir() function

Another option to list all files and subdirectories inside a directory is to use the readdir() function. The idea is to open the directory handle with opendir() and make repeated calls to the readdir() function to get the name of the next entry in the directory. Unlike scandir(), the files are returned in the same order as they’re stored in the filesystem. The following solution shows the use of the readdir() function to list out all entries in the current directory without . and ...

Download Code

3. Using glob() function

Another good alternative is to use the glob() function to list all the files and folders in a directory. The glob() function searches for the specified pattern and returns an array containing the matched pathnames. To filter the returned array for files only, you can use the array_filter() function with is_file() as the callback.

Download Code

4. Using DirectoryIterator class

The SPL provides a set of iterators for traversing objects in PHP. It has a DirectoryIterator class that provides a simple interface for viewing the contents of filesystem directories. You can iterate over the directory contents using a directory iterator and process only entries that return true for the DirectoryIterator::isFile() function.

Download Code

5. Using RecursiveDirectoryIterator class

If you need to list files present in the subdirectories as well, you can use the RecursiveDirectoryIterator class. It provides an interface for iterating recursively over filesystem directories. The following script recursively list all files present in a directory and its subdirectories. It uses DirectoryIterator::isFile() to determine if the current item is a regular file.

Download Code

That’s all there is to listing all files in a directory in PHP.