Loop code for each file in a directory

Chiggins picture Chiggins · May 27, 2011 · Viewed 171.8k times · Source

I have a directory of pictures that I want to loop through and do some file calculations on. It might just be lack of sleep, but how would I use PHP to look in a given directory, and loop through each file using some sort of for loop?

Thanks!

Answer

Emil Vikström picture Emil Vikström · May 27, 2011

scandir:

$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or glob may be even better for your needs:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}