Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only images using scandir in PHP?

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

$dir    = '/tmp'; $files1 = scandir($dir); 
like image 229
esafwan Avatar asked Jul 12 '10 07:07

esafwan


People also ask

What does Scandir do in PHP?

The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.

How do I display all images in a directory in HTML?

<? php $files = scandir('path/to/img/directory/'); foreach($files as $file) { if($file !== "." && $file !== "..") { echo "<img src='$file' />"; } } ?>


1 Answers

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.

like image 81
Gordon Avatar answered Sep 20 '22 00:09

Gordon