Coder Perfect

Each file in a directory has its own loop code. [duplicate]

Problem

I have a folder of images that I’d like to loop through and perform some file calculations on. It could just be a lack of sleep, but how would I use PHP to look in a specified directory and use a for loop to loop through each file?

Thanks!

Asked by Chiggins

Solution #1

scandir:

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

or glob might be a better option for you:

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

Answered by Emil Vikström

Solution #2

Check out the DirectoryIterator class.

One of the comments on that page reads, “

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

RecursiveDirectoryIterator is the recursive variant.

Answered by squirrel

Solution #3

Looks for the glob() function:

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

Answered by fvox

Solution #4

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 />";  
}  

Answered by Phill Pafford

Solution #5

To perform whatever is possible, use the glob function in a foreach loop. In the example below, I also used the file exists function to see if the directory existed before proceeding.

$directory = 'my_directory/';
$extension = '.txt';

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

Answered by TURTLE

Post is based on https://stackoverflow.com/questions/6155533/loop-code-for-each-file-in-a-directory