How to get only images using scandir in PHP?

Viewed 80306

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

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

If you would like to scan a directory and return filenames only you can use this:

$fileNames = array_map(
    function($filePath) {
        return basename($filePath);
    },
    glob('./includes/*.{php}', GLOB_BRACE)
);

scandir() will return . and .. as well as the files, so the above code is cleaner if you just need filenames or you would like to do other things with the actual filepaths

I wrote code reusing and putting together parts of the solutions above, in order to make it easier to understand and use:

<?php
//put the absolute or relative path to your target directory
$images = scandir("./images");
$output = array();
$filer = '/(.jpg|.png|.jpeg|.gif|.bmp))/';
foreach($images as $image){
  if(preg_match($filter, strtolower($image))){
    $output[] = $image;
  }
}
var_dump($output);
Related