tags:

views:

122

answers:

3

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.

+5  A: 

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.

Greg
You might want to add a `$` to your regex.
Gumbo
Oops yeah... 15 chars :|
Greg
+2  A: 

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

maxim
+2  A: 

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;
}
cpharmston
your while condition is really redundant. if it's true, you obviously won't need to *specify* it as !== false
contagious
Whoops, good catch. I repurposed some old code where that was necessary. Fixed. Thanks!
cpharmston
just add recursion and your done.
Pim Jager