Loop code for each file in a directory

PhpImageFilesystemsDirectory

Php Problem Overview


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!

Php Solutions


Solution 1 - Php

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
}

Solution 2 - Php

Check out the DirectoryIterator class.

From one of the comments on that page:

// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

The recursive version is RecursiveDirectoryIterator.

Solution 3 - Php

Looks for the function http://www.php.net/manual/en/function.glob.php">glob()</a>;:

<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
    echo $jpg, "\n";
}
?>

Solution 4 - Php

Try GLOB()

$dir = "/etc/php5/*";  
  
// Open a known directory, and proceed to read its contents  
foreach(glob($dir) as $file)  
{  
    echo "filename: $file : filetype: " . filetype($file) . "<br />";  
}  

Solution 5 - Php

Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.

$directory = 'my_directory/';
$extension = '.txt';
    
if ( file_exists($directory) ) {
   foreach ( glob($directory . '*' . $extension) as $file ) {
      echo $file;
   }
}
else {
   echo 'directory ' . $directory . ' doesn\'t exist!';
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChigginsView Question on Stackoverflow
Solution 1 - PhpEmil VikströmView Answer on Stackoverflow
Solution 2 - PhpsquirrelView Answer on Stackoverflow
Solution 3 - PhpfvoxView Answer on Stackoverflow
Solution 4 - PhpPhill PaffordView Answer on Stackoverflow
Solution 5 - PhpTURTLEView Answer on Stackoverflow