Reading the Contents of a Directory
Let's start with simple listing the contents of a directory. We need three functions to perform this task: opendir(), readdir() and closedir(). The opendir() function takes one parameter, which is the directory we want to read, and returns a directory handle to be used in subsequent readdir() and closedir() calls. opendir() returns False if the directory could not be opened.
The readdir() function takes one parameter, which is the handle that opendir() returned and each time we call readdir() it returns the filename of the next file in the directory. readdir() returns False if the end of the directory has been reached. Note that readdir() returns only the names of its items, rather than full paths.
The example below creates a select box that lists all the files in a directory. Copy and paste this code and save it as index.php in a directory you wish do display all files for. It automatically excludes itself from the list, and is easy to modify to make it ignore other files as well:
First, we open the directory for reading with the opendir() function and use a while statement to loop through each of its entries. We call readdir() as part of the while statement's test expression, assigning its result to the $fname variable. We are explicitly testing whether the return value is equal to and of the same type as False since otherwise, any directory entry whose name evaluates to False will stop the loop prematurely. Within the body of the while statement, we check if the file is not this file, and does not start with a . (current directory) or .. (parent directory) and then store the file name into the $files array. We also do one more check. If a full file path leads to a directory then we add to the file name "(Dir)".
There is another way to iterate over all files in a directory. PHP 5 has a set of objects called iterators. Iterators help eliminate problems in your code. For instance, PHP 5 provides a DirectoryIterator:
This example produces the same results as the earlier code that uses the directory functions, but this code is shorter and safer because you cannot forget the !== = comparison.