24.7.1. ProblemYou want to iterate over all files in a directory. For example, you want to create a <select/> box in a form that lists all the files in a directory. 24.7.2. SolutionUse a DirectoryIterator to get each file in the directory, as in Example 24-20. Processing all files in a directory
24.7.3. DiscussionThe DirectoryIterator yields one value for each element in the directory. That value is an object with some handy characteristics. The object's string representation is the filename (with no leading path) of the directory element. For example, if /usr/local/images contains the files cucumber.gif and eggplant.png, Example 24-20 prints: <select name='file'> <option>.</option> <option>..</option> <option>cucumber.gif</option> <option>eggplant.png</option> </select> A DirectoryIterator yields an object for all directory elements, including . (current directory) and .. (parent directory). Fortunately, that object has some methods that help us identify what it is. The isDot( ) method returns true if it's either . or ... Example 24-21 uses isDot( ) to prevent those two entries from showing up in the output. Removing . and .. from output
Table 24-4 lists the other methods available on the objects that a DirectoryIterator yields.
The data that the functions in Table 24-4 report come from the same underlying system calls as the data that the functions in Table 24-1 report, so the same cautions on differences between Unix and Windows apply. 24.7.4. See AlsoDocumentation on DirectoryIterator at http://www.php.net/~helly/php/ext/spl/classDirectoryIterator.html. |