tags:

views:

52

answers:

3

Is there any way to get only images (jpeg,png&gif) while using:

$dir    = '/tmp';
$files1 = scandir($dir);
+1  A: 

You can search the resulting array afterward and discard files not matching your criteria.

scandir does not have the functionality you seek.

Borealid
+5  A: 

You can use glob

$images = glob('/tmp/*.{jpeg,gif,png}', GLOB_BRACE);

If you need this to be case-insensitive, you could use a DirectoryIterator in combination with a RegexIterator or pass the result of scandir to array_map and use a callback that filters any unwanted extensions. If you use strpos, fnmatch or pathinfo to get the extension is up to you.

Gordon
That... doesn't use `scandir()` anymore. But is otherwise correct. So shouldn't that be "no, with `glob`"?
Borealid
@Borealid nitpicker :D
Gordon
Now make it case insensitive. >:)
salathe
@salathe evil hearted you!! :P
Gordon
+1  A: 

I would loop through the files and look at their extensions:

$dir = '/tmp'
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $ext = substr($fileName, strrpos($fileName, '.') + 1);
    if(in_array($ext, array("jpg","jpeg","png","gif"))
        $files1[] = $filename;
}
Josiah