Reading Directories, the easy way!

Well, I just answered a question in the forums and it struck me that this is a common problem so thought i’d post the solution here for anyone looking for this type of thing. :slight_smile:

This allows us to read any directory including all sub-directories of the starting point.

Ready? Let’s go…

Firstly we are going to create a function - functions are great!
They keep our code in one place and doesn’t interfere with other code on our page. :slight_smile:
[php]
// this function takes two args: a string and an array.
// $path = string. The path to a folder.
// $imgtype = array. An array of file types to look for.
function list_files($path, $type) {
$directory = new \RecursiveDirectoryIterator($path);
$iterator = new \RecursiveIteratorIterator($directory);
$files = array();
foreach ($iterator as $info) {
if (in_array($info->getExtension(), $type)) {
$files[] = $info->getPathname();
}
}
return $files;
}
[/php]

Now, to use our newly created function, we do this:
[php]
$path = ‘imgs’; // start in this folder/directory
$type = array(‘png’, ‘jpg’); // find me this type of file…
$image_array = list_files($path, $type); // do it
[/php]

We now have a nice array of all the files found.
In this example we searched for files with an extension of ‘png’ or ‘jpg’

  • we could indeed search for anything we want, IE: ‘php’ etc.

Let’s take a look at what we found…
[php]
// display the results
print ‘

’;
print_r($image_array);
print ‘
’;
/*
output:
Array
(
[0] => imgs\cat.png
[1] => imgs\dog.png
[2] => imgs\mouse.jpg
[3] => imgs\more_images\cat2.png
[4] => imgs\more_images\dog2.png
[5] => imgs\more_images\mouse2.jpg
)
[/php]

Yep, that’s all folks!!
Searching directories has never been easier thanks to your friendly Redscouse! :slight_smile:

Enjoy,
Red :wink:

Very Useful!

Sponsor our Newsletter | Privacy Policy | Terms of Service