How to get only images using scandir in PHP?

esafwan picture esafwan · Jul 12, 2010 · Viewed 72k times · Source

Is there any way to get only images with extensions jpeg, png, gif etc while using

$dir    = '/tmp';
$files1 = scandir($dir);

Answer

Gordon picture Gordon · Jul 12, 2010

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. Whether you use strpos, fnmatch or pathinfo to get the extension is up to you.