Finding Paths, Timestamps and More with the DirectoryIterator Class in PHP

Are you interested in having at your disposal a quick reference for working with the “DirectoryIterator” class that comes with PHP 5? Then this might be the article that you’ve been waiting for! Welcome to the second tutorial of the series “A Close Look at the DirectoryIterator Class in PHP 5.” Over the course of this set of installments, you’ll find complete coverage of the most important methods bundled with this class, and learn how to take advantage of their excellent functionality.

Introduction

If you’ve read the previous article, you probably have a better idea now of how the “DirectoryIterator” class does its business. As you’ll certainly remember, all the code samples that were shown in that article were aimed at demonstrating how easy this class makes it to traverse a specified directory.

Having at hand such a useful piece of code, there’s no need to create custom classes to deal with the contents of any directory, since the mentioned class can traverse a directory by using a regular “foreach” loop. In addition, the class on its own comes packaged with a bunch of handy methods which can be used for moving the iterator’s pointer back and forward,  as well as obtaining complete information on the size, type, paths, etc. of the files contained within the selected directory.

If the wealth of impressive features exposed by this class isn’t enough for you, I have still more material to show you in the next few lines. Now that I have your attention, in this second part of the series I’ll continue exploring new methods that come with the “DirectoryIterator” class, including those that use additional capabilities to determine the full path and name of directory elements, their modification timestamps, and much more.

Having established the goals of this article, it’s time to jump forward and keep learning more about the “DirectoryIterator” class. Let’s get going!

{mospagebreak title=Learning the rewind(), current() and valid() methods}

Indeed, the title of this section is particularly significant, because it suggests concretely the implementation of three new methods that come with the “DirectoryIterator” class. Of course, here I’m talking about the “rewind(),” “current()” and “valid()” methods respectively, which can be fairly useful in those cases where you need to extend the functionality brought by the respective base class.

Basically, these three methods behave as expected inside an iterator class, since they allow one to move across a specific directory as if one were working with regular arrays. But let’s turn away from the boring theory for a moment and see a practical example, which demonstrates the implementation of these three methods in one single class. Please look at the class shown below:

class DirectoryProcessor extends DirectoryIterator{
    private $dirPath;
    public function __construct($dirPath=’default_path/’){
        parent::__construct($dirPath);
    }
    public function rewind(){
        parent::rewind();
    }
    public function current(){
        return ‘Path of current element is ‘.parent::getPath().’
and its size in bytes is ‘.parent::getSize();
    }
    public function valid(){
        if(parent::valid()){
            return true;
        }
        return false;
    }
}

In short, what I’ve done above is derive a subclass from the original “DirectoryIterator” to extend the functionality provided by the respective “current()” method. Even when this example is extremely comprehensive with reference to its source code, it also shows in a nutshell how the “DirectoryIterator” class can be easily expanded, particularly in those situations where you need to implement additional features aside from the existing ones.

Returning to the previously defined subclass, here is a short script that iterates over a sample “default_path” directory, and displays all the paths of the files contained inside of it:

$dirProc=new DirectoryProcessor;
foreach($dirProc as $dirContent){
   
echo $dirContent.'<br />';
}

Basically, the above code snippet shows how to use the “DirectoryProcessor” class, which as you learned previously is simply a child class derived from “DirectoryIterator.” The pertinent output of this example is shown below:

Path of current element is default_path and its size in bytes is 0
Path of current element is default_path and its size in bytes is 0
Path of current element is default_path and its size in bytes is 31
Path of current element is default_path and its size in bytes is 31

As you can see, demonstrating how the “rewind(),” “current()” and “valid()” methods work together within the same child class is not only a simple process, but it’s also instructive!

Okay, I firmly believe that the example you saw before is pretty easy to understand, therefore let’s move on and continue exploring the methods exposed by the “DirectoryIterator” class. The following section explains precisely how to use the “getFileName()” and “isFile()” methods, so I suggest you keep reading to learn more about them.

{mospagebreak title=Using the getFileName() and isFile() methods}

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.

{mospagebreak title=Using the getMTime(), getATime(), and getCTime() methods}

As you’ll probably agree, a decent directory iterator class wouldn’t be complete if it’s not capable of dealing with timestamps. Fortunately, the “DirectoryIterator” class won’t disappoint you (at least regarding this specific aspect), since it’s been provided with some interesting methods that retrieve information related to different timestamps.

First, take a look at the “getMTime()” method listed below, which returns the last modification timestamp of a given directory element:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isFile()){
        echo ‘Last modification timestamp of current file is : ‘.$dirContent->getMTime().'<br />';
    }
}

In this case, the “getMTime()” method used above simply returns the last modification timestamp of the current directory element, which displays the following results, based on the two text files that I used in the previous section:

Last modification timestamp of current file is : 1149698631
Last modification timestamp of current file is : 1149698651

All right, now that you know how to use the “getMTime()” method shown above, take a look at the following code. In this case, I’m referencing the handy “getATime()” method, which returns the timestamp of the last access to a given directory element. Its implementation is as follows:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isFile()){
        echo ‘Last modification timestamp of current file is :
‘.$dirContent->getATime().'<br />';
    }
    else{
        echo ‘Last modification timestamp of current directory
is : ‘.$dirContent->getATime().'<br />';
    }
}

As you can see, the above example illustrates a basic approach for how to use the “getATime()” method that I mentioned earlier. In particular, the script loops over the selected directory and displays the last access timestamps of both directories and files contained within the directory in question.

Based on the logic applied by the prior example, the outputted results are listed below:

Last modification timestamp of current directory is : 1150153955
Last modification timestamp of current directory is : 1150152774
Last modification timestamp of current file is : 1149698631
Last modification timestamp of current file is : 1149698651

As you may have realized, the “getATime()” method that you learned previously is not difficult to grasp, so let me show you another one which can be handy for retrieving the inode timestamp of a given directory element. Its implementation is as follows:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isFile()){
        echo ‘Last inode modification timestamp of current file
is : ‘.$dirContent->getCTime().'<br />';
    }
    else{
        echo ‘Last inode modification timestamp of current
directory is : ‘.$dirContent->getCTime().'<br />';
    }
}

Just in case you’re wondering what the term “inode” means, let me tell you that it’s short for “Index Node,” that is the sector of the hard disk that contains information about a specific directory or file, such as its name, permissions, etc.

Okay, now that you understand the word “inode,” take a moment to examine the output generated by the script listed a few lines above:

Last inode modification timestamp of current directory is : 1149698503
Last inode modification timestamp of current directory is : 1149696540
Last inode modification timestamp of current file is : 1149698631
Last inode modification timestamp of current file is : 1149698651

As you’ll realize, after studying all the previous examples, the “DirectoryIterator” class has been provided with a great package of timestamp-related methods that suit the most common requirements of a web application that works intensively with the file system. The process is reduced to selecting the appropriate method that best fits your needs.

At this point, we’re almost done for now. Nevertheless, there’s still one more section that I’d like you to read before you get too tired, because it’ll show you how to use two concrete methods called “getPath()” and “getPathName()” respectively.

As you’ll see, they’ll allow you to retrieve the corresponding path of any directory element, so jump straight into the following section. I’ll be there, waiting for you.

{mospagebreak title=Using the getPath() and getPathName() methods}

As I mentioned before, the last two methods that I’ll cover in this tutorial are “getPath()” and “getPathName().” The first one, as the name suggests, returns the path of the selected directory, while the second one retrieves the path and filename of the current directory element.

Regarding the first method, here’s an example of how to use it. Check it out:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isFile()){
        echo ‘Path of current file is : ‘.$dirContent->getPath
().'<br />';
    }
    else{
        echo ‘Path of current directory is : ‘.$dirContent-
>getPath().'<br />';
    }
}

As you can see, whether the current element being traversed is a file or a directory, the value returned by the “getPath()” method is the same. This fact is clearly demonstrated by the below results:

Path of current directory is : default_path
Path of current directory is : default_path
Path of current file is : default_path
Path of current file is : default_path

Now that you understand how the “getPath()” method works, turn your attention to the next one, that is “getPathName(),” which returns slightly more detailed information about the current directory entry. A possible implementation for this method can be seen below:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isFile()){
        echo ‘Path of current file is : ‘.$dirContent-
>getPathName().'<br />';
    }
    else{
        echo ‘Path of current directory is : ‘.$dirContent-
>getPathName().'<br />';
    }
}

Logically, the previous script outputs the following values for each directory element:

Path of current directory is : default_path/.
Path of current directory is : default_path/..
Path of current file is : default_path/file1.txt
Path of current file is : default_path/file2.txt

Okay, after covering some of the most relevant methods included with the “DirectoryIterator” class, probably you’ll have realized its awesome capabilities for dealing with timestamps, paths and index nodes. If you’re currently developing PHP applications that do a lot of work with directories, then consider including this class in your toolbox.

To wrap up

In this second article of the series, I took an in-depth look at some helpful methods packaged with the “DirectoryIterator” class that can help you obtain information on timestamps, paths and index nodes of directory entries

However, there’s a few more methods worth covering with reference to this class in particular, thus in the last article, I’ll be explaining them, of course accompanied by copious hands-on examples. Meet you in the last part!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort