Recursive File Search (PHP)

Jason picture Jason · Dec 7, 2009 · Viewed 43.3k times · Source

I'm trying to return the files in a specified directory using a recursive search. I successfully achieved this, however I want to add a few lines of code that will allow me to specify certain extensions that I want to be returned.

For example return only .jpg files in the directory.

Here's my code,

<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
foreach(new RecursiveIteratorIterator($it) as $file) {
echo $file . "<br/> \n";
}
?>

please let me know what I can add to the above code to achieve this, thanks

Answer

Jan Hančič picture Jan Hančič · Dec 7, 2009
<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
$display = Array ( 'jpeg', 'jpg' );
foreach(new RecursiveIteratorIterator($it) as $file)
{
    if (in_array(strtolower(array_pop(explode('.', $file))), $display))
        echo $file . "<br/> \n";
}
?>