user4543981
user4543981

Reputation:

how to list all image files in folder?

I want to have a list of only image files in a certain folder. I tried this, but doesn't work for all files:

$files = scandir("/folder/");
foreach($files as $file) {
  if (substr($string, -4) == '.jpg'){
   $f[] = $file; 
 }

What would be the right way?

Upvotes: 1

Views: 173

Answers (1)

Alex
Alex

Reputation: 6037

First get all the files, but leave out the ones starting with "." Then a simple preg_match to get all image files

$files = array_diff( scandir("/folder/"), array(".", "..") ); 

$images = array()
for ($file in $file){
 if (preg_match("/\.(jpg|jpeg|png)$/", $file)){
   $images[] = $file;   
 }
}

or

$images = glob("/folder/*.{jpg,gif,png,jpeg}", GLOB_BRACE);

Upvotes: 2

Related Questions