Benoît Pointet
Benoît Pointet

Reputation: 898

listing all jpg files in dir and subdirs

How can I list all jpg files in a given directory and its subdirectories in PHP5 ?

I thought I could write a glob pattern for that but I can't figure it out.

thanx, b.

Upvotes: 0

Views: 994

Answers (3)

Greg
Greg

Reputation: 321618

You can use a RecursiveDirectoryIterator with a filter:

class ImagesFilter extends FilterIterator
{
    public function accept()
    {
        $file = $this->getInnerIterator()->current();
        return preg_match('/\.jpe?g$/i', $file->getFilename());
    }
}

$it = new RecursiveDirectoryIterator('/var/images');
$it = new ImagesFilter($it);

foreach ($it as $file)
{
    // Use $file here...
}

$file is an SplFileInfo object.

Upvotes: 5

c_harm
c_harm

Reputation:

Wish I had time to do more & test, but this could be used as a starting point: it should (untested) return an array containing all the jpg/jpeg files in the specified directory.

function load_jpgs($dir){
    $return = array();
    if(is_dir($dir)){
        if($handle = opendir($dir)){
            while(readdir($handle)){
                echo $file.'<hr>';
                if(preg_match('/\.jpg$/',$file) || preg_match('/\.jpeg$/',$file)){
                    $return[] = $file;
                }
            }
            closedir($handle);
            return $return;
        }
    }
    return false;
}

Upvotes: 2

maxim
maxim

Reputation: 166

without doing it for you. recursion is the answer here. a function that looks in a dir and gets a list of all files. filters out only th jpg's then calls its self if i finds any sub dirs

Upvotes: 2

Related Questions