Recursively Process A Directory Using DirectoryIterator In PHP5


Perhaps one of the most used features of PHP5 for me are the great new in-built iterators, more specifically the DirectoryIterator and RecursiveDirectoryIterator functions. Using these saves a lot of time hand-coding the logic behind listing files in a directory on the local machine as these new iterator functions handle all that legwork themselves.

For those of you who are unsure as to what an iterator is, its basically an object that is able to ‘cycle’ through occurrences of other objects. It doesn’t matter if we are cycling through a bunch of letters, numbers or files in a directory, iteration is a key programming concept that is a fundamental building block of most programs.

You may have seen the usage of a numeric iterator before (say $i):

<?php
$i = 0;


for($i=0;$i<=10;$i++)
{
echo “Number is equal to: “ . $i
}


?>

Processing A Single Level Directory:

A simple example of the use of the (much simpler) DirectoryIterator function can be seen below:

<?php
$it = new DirectoryIterator("/tmp/mystuff");
foreach( as ) 
{ if (!->isDot())
{ echo . "\n"; } } ?>

Processing A Multi-Level Directory (Nested):

<?php
$it = new RecursiveDirectoryIterator("/tmp");
foreach(new RecursiveIteratorIterator() as ) 
{ echo . "\n"; } ?>

In this case, the output should now include a list of all the files and directories under the starting directory (very handy for when you want to quickly print and dig down into multiple levels of a directory tree!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s