Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive File Search (PHP)

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

like image 828
Jason Avatar asked Dec 07 '09 14:12

Jason


3 Answers

<?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";
}
?>
like image 194
Jan Hančič Avatar answered Nov 12 '22 10:11

Jan Hančič


You should create a filter:

class JpegOnlyFilter extends RecursiveFilterIterator
{
    public function __construct($iterator)
    {
        parent::__construct($iterator);
    }

    public function accept()
    {
        return $this->current()->isFile() && preg_match("/\.jpe?g$/ui", $this->getFilename());
    }

    public function __toString()
    {
        return $this->current()->getFilename();
    }
}

$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
$it = new JpegOnlyFilter($it);
$it = new RecursiveIteratorIterator($it);

foreach ($it as $file)
    ...
like image 20
Greg Avatar answered Nov 12 '22 09:11

Greg


Try this, it uses an array of allowed file types and only echos out the file if the file extension exists within the array.

<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
$allowed=array("pdf","txt");
foreach(new RecursiveIteratorIterator($it) as $file) {
    if(in_array(substr($file, strrpos($file, '.') + 1),$allowed)) {
        echo $file . "<br/> \n";
    }
}
?>

You may also find that you could pass an array of allowed file types to your RecursiveDirectoryIterator class and only return files that match.

like image 7
Ben Everard Avatar answered Nov 12 '22 11:11

Ben Everard