Finding Paths, Timestamps and More with the DirectoryIterator Class in PHP - Using the getFileName() and isFile() methods
(Page 3 of 5 )
As I mentioned at the end of the previous section, the “DirectoryIterator” class has many more methods that can make your life much easier when it comes to processing directories and their corresponding files. In this particular situation, I’ll show you how to use two entirely new methods that belong to this class: the “getFile()” and “isFile()” methods respectively.
In most cases, a hands-on example can be much more instructive than some boring sentences. So the use of the methods that I mentioned before is illustrated by the following script. Take a look:
$dirProc=new DirectoryIterator('default_path/');
foreach($dirProc as $dirContent){
if($dirContent->isFile()){
echo 'Name of current file is : '.$dirContent-
>getFileName().'<br />';
}
}
In this case, the example above first loops over the selected directory and checks for the files included in it by using the corresponding “isFile()” method (by the way, this is very similar to the “is_file()” PHP native function, isn’t it?), and finally displays their names by the “getFileName()” method.
Now, after examining the logic of the previous script, and assuming that the selected “default_path” contains two files, “file1.txt” and “file2.txt” respectively, have a look at the output generated by it:
Name of current file is : file1.txt
Name of current file is : file2.txt
As shown in the example you learned before, retrieving the names of the files that might be included within a specific directory is really a straightforward process that doesn’t bear a longer discussion. However, this journey isn’t over yet, since the “DirectoryIterator” class also comes packaged with an excellent set of methods, specifically to deal with timestamps of directories and files.
That’s exactly the subject that I’ll discuss in the upcoming section, which certainly is a good reason for you to keep on reading. To learn more about these new methods, please click on the link below.
Next: Using the getMTime(), getATime(), and getCTime() methods >>
More PHP Articles
More By Alejandro Gervasio