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
Regarding the top voted answer: I created this code which is using fewer functions, only 3,
isset()
,array_flip()
,explode()
instead of 4 functions. I tested the top voted answer and it was slower than mine. I suggest giving mine a try:Let PHP do the job:
You should create a filter:
Try this, it uses an array of allowed file types and only echos out the file if the file extension exists within the array.
You may also find that you could pass an array of allowed file types to your
RecursiveDirectoryIterator
class and only return files that match.You might want to check out this page about using glob() for a similar search:
http://www.electrictoolbox.com/php-glob-find-files/