Using Introspective Methods with the DirectoryIterator Class in PHP 5

If you’re one of those PHP developers who want to explore the package of classes that come bundled with the Standard PHP Library (SPL), then fear not, because you’re at the right place. Welcome to the concluding part of the series “A Close Look at the DirectoryIterator Class in PHP 5.” In three parts, this series introduces the most important methods attached to this class, and shows you how to use them by mean of extensive hands-on examples.

Introduction

After this short introduction, allow me to recapitulate briefly the topics that I covered in the two previous articles. This will conveniently refresh your memory and get you back into the flow of the contents of this series.

As you’ll probably remember, over the course of the first article, I took an in-depth look at some of the core methods included within the “DiretoryIterator” class to demonstrate how a specified directory can be quickly traversed by a regular “foreach” language construct. In all the code samples that you saw, once an instance of the iterator class was properly created, the process for iterating over several directory entries was simplified to using the mentioned loop structure, in conjunction with a conventional array notation.

Aside from depicting the entire process for traversing a given directory and accessing each of its elements, in the second part of this series, strong emphasis was put on covering some of the most relevant methods that come with the “DirectoryIterator” class. In accordance with this, you learned how to do all sorts of clever things, like finding paths and names of directory entries, as well as handling the corresponding timestamps.

Perhaps you think that after having examined all the methods that I mentioned before, the tale of the “DirectoryIterator” class was already concluded. Well, not so fast; this class still has some additional methods that require special attention. For this reason, this last tutorial of the series will be focused mostly on covering all the methods related to performing some kind of introspective process, which can be quite useful when analyzing the types and permissions of each entry included in a given directory.

Having established the goals of this tutorial, let’s get started. Hopefully, this will be an educational experience!

{mospagebreak title=The isDir() method}

Indeed, one of the most useful methods that comes with the “DirectoryIterator” class is the one called “isDir().” As its name indicates, this method is capable of determining whether a specific entry is a directory or not. Although this ability may look pretty basic at first glance, the truth is that it can be handy in those cases where you need to spot the differences between directories and plain files.

Of course all this theory sounds good, but it’s time to see how the “isDir()” method can be used in a concrete case. The example shown below demonstrates a basic implementation:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isDir()){
        echo ‘Current element is a directory and its path is the
following : ‘.$dirContent->getPathName().'<br />';
    }
    else{
        echo ‘Current element is a file and it path is the
following : ‘.$dirContent->getPathName().'<br />';
}

That’s all you need to get the “isDir()” method working. As you can see, the above script shows how to find out whether a directory entry is also a sub directory itself, or a regular file. Based on the sample directory that I used in previous tutorials, the results outputted by the previous example would be the following:

Current element is a directory and its path is the following : default_path/.
Current element is a directory and its path is the following : default_path/..
Current element is a file and it path is the following : default_path/file1.txt
Current element is a file and it path is the following : default_path/file2.txt

The listing shown above demonstrates basically how the prior script works after using the mentioned “isDir()” method. Here, I’d like to highlight the importance of this method; its functionality can be used as the starting point for building more sophisticated applications, for example a recursive directory iterator (even when the SPL package also includes a recursive iterator class).

Well, now you’ve seen in action one of the introspective methods included with the “DirectoryIterator” class. But it’s time to move on and review others which can be also helpful in determining different types of entries present within a specified directory.

Specifically, in the next few lines, I’ll take a look at the “isDot()” method, which also uses the introspective capabilities of the “DirectoryIterator” class. If you’re interested in how this method works, please click on the link below and continue reading.

{mospagebreak title=Using the isDot() method}

The natural introspective abilities that were included with the “DirectoryIterator” class allow you, among other things, to determine whether a given directory entry is  “.” or “:”. This checking process can be easily performed by using the “isDot()” method, which has been utilized in the example below. Please examine its source code:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isDot()){
        echo ‘Current element is “.” or “:” and its path is the
following : ‘.$dirContent->getPathName().'<br />';
    }
    else{
        echo ‘Current element is a regular file and it path is
the following : ‘.$dirContent->getPathName().'<br />';
    }
}

In this case, the above code snippet illustrates in a friendly fashion how to use the “isDot()” method, in order to determine whether the current directory element is “.” or “:”. Regarding the results outputted by this example, they’re listed below:

Current element is “.” or “:” and its path is the following : default_path/.
Current element is “.” or “:” and its path is the following : default_path/..
Current element is a regular file and it path is the following : default_path/file1.txt
Current element is a regular file and it path is the following : default_path/file2.txt

Assuming that you had no major problems understanding the previous example, I’m pretty sure that you’re starting to realize the great introspective capabilities natively exposed by the “DirectoryIterator” class. They’re indeed remarkable!

Okay, now that you know how the “isDot()” method works, let’s leap forward quickly and look at three new methods that belong to the “DirectoryIterator” class, which also use introspection to determine whether a specific directory entry is readable, writable and executable.

Sounds really interesting, right? Therefore, I recommend you read the following section to find out how the methods that I mentioned before can be put to work.

{mospagebreak title=Implementing the isExecutable(), isReadable() and isWritable() methods}

Perhaps this doesn’t happen to you so frequently during the development of an application, but there are times where you need to know if a particular file is executable, or if different users has the proper permissions for reading and writing data to that file.

In this case, the “DirectoryIterator” class makes performing all these tasks a no-brainer process by using the “isExecutable()”, “isReadable()” and “isWritable()” methods respectively. Since I want you to understand how each method works separately, below I coded three consecutive examples that show the functionality brought by each of them:

// implements ‘isExecutable()’ method
$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isExecutable()){
        echo ‘Current element is a executable file and its path
is the following : ‘.$dirContent->getPathName().'<br />';
    }
}
// displays the following:>
/*
Current element is a executable file and its path is the following : default_path/Firefox Setup 1.5.0.2.exe

*/
// implements ‘isReadable()’ method
$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isReadable()){
        echo ‘Current element is readable and its path is as
follows : ‘.$dirContent->getPathName().'<br />';
    }
    else{
        echo ‘Current element is not readable.<br />';
    }
}
// displays the following:
/*
Current element is readable and its path is as follows :
default_path/.
Current element is readable and its path is as follows :
default_path/..
Current element is readable and its path is as follows :
default_path/file1.txt
Current element is readable and its path is as follows :
default_path/file2.txt

*/
// implements ‘isWritable()’ method
$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    if($dirContent->isWritable()){
        echo ‘Current element is writable and its path is as
follows : ‘.$dirContent->getPathName().'<br />';
    }
    else{
        echo ‘Current element is not writable and its path is as
follows : ‘.$dirContent->getPathName().'<br />';
    }
}
// displays the following:
/*
Current element is writable and its path is as follows :
default_path/.
Current element is writable and its path is as follows :
default_path/..
Current element is not writable and its path is as follows :
default_path/file1.txt
Current element is writable and its path is as follows :
default_path/file2.txt
*/

After listing the three previous examples, I’m sure that you’ve understood correctly how they work. First the “isExecutable()” method is used to determine whether or not a specific file is executable. In this case, I purposely included Firefox’s installer, so the script in question can display the corresponding message when this file is examined.

Now, with reference to the second case, you’ll realize that the script iterates over all the elements of the sample directory and checks to see whether they’re readable. In this specific instance, I decided to turn all the directory entries into readable pieces, but as you know, this condition might be easily changed, and assign different permissions to each directory element.

Finally, the third example shows a straight implementation of the “isWritable()” method, which also traverses all the respective directory elements, and checks to see if each of them have the proper permissions for writing data. As you’ll realize, all the methods that I exemplified before are pretty intuitive to implement, therefore you shouldn’t have any problems using them.

Fine, after demonstrating some practical examples of how to utilize the “isExecutable(),” “isReadable()” and “isWritable()” methods, which are included with the “DirectoryIterator” class, it’s time to jump forward and take a quick look at a couple of additional introspective ones.

In this case, I’m talking about the “getPerms()” and “getType()” methods, where the first one can be used for obtaining the accessing permissions of a given directory entry, while the second one comes in handy for checking its type.

Since these methods will be covered in the upcoming section, I recommend that you click on the link below and keep reading.

{mospagebreak title=The getPerms() and getType() methods}

If all the methods that you learned before seemed fairly easy to grasp, then these will be even simpler. First, look at the example below, which shows how to use the “getPerms()” method to obtain the permission codes that correspond to each directory entry:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    echo ‘Current element has the following
permissions :’.$dirContent->getPerms().'<br />';
}

In this case, the script shown above loops over the sample “default_path” directory and retrieves all the permission codes that were given to each directory element. After executing this snippet, it displays the following results:

Current element has the following permissions :16895
Current element has the following permissions :16895
Current element has the following permissions :33206
Current element has the following permissions :33206

Due to the simplicity of the “getPerms()” method, allow me to skip over it rapidly, and show you the last example of this tutorial. In this case, I’m referencing directly the “getType()” method, which can be handy in those situations where you need to determine the type of a particular directory entry, that is if it’s a directory or a file. Please, look at the sample code below:

$dirProc=new DirectoryIterator(‘default_path/’);
foreach($dirProc as $dirContent){
    echo ‘Type of current element is the following :
‘.$dirContent->getType().'<br />';
}

As you can see, the method used above is equivalent to utilizing a combination of the “isDir()” and “isFile()” methods that were opportunely exemplified earlier. Therefore, in accordance with the above script, the following results are displayed:

Type of current element is the following : dir
Type of current element is the following : dir
Type of current element is the following : file
Type of current element is the following : file
Type of current element is the following : file

As you’ll realize, determining whether a directory entry is a subdirectory or a file is a task that can be easily carried out by the “getType()” method. Use the above script’s source code and utilize different directories to see what kind of output you get in each case. I use this technique when I get bored and fun comes up automatically!

Final thoughts

Finally, this series is finished. I hope you found it enjoyable and instructive, particularly if you’re starting to discover the power behind the SPL package. Of course, there are many more predefined classes aside from “DirectoryIterator” that can make your life easier when using PHP 5. Therefore, I suggest you to take a look at the PHP manual to learn more about them. See you in the next PHP tutorial!

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

chat sex hikayeleri Ensest hikaye