Loop code for each file in the directory

I have a catalog of images that I want to execute and do some file calculations. It may just be a lack of sleep, but how can I use PHP to search in a given directory and scroll through each file using some kind of for loop?

Thank!

+95
directory filesystems php image
May 27 '11 at 17:08
source share
5 answers

scandir :

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

or glob might be even better for your needs:

 $files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE); foreach($files as $file) { //do your work here } 
+247
May 27 '11 at 17:11
source share

Check out the DirectoryIterator class.

From one of the comments on this page:

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

Recursive version of RecursiveDirectoryIterator .

+56
May 27 '11 at 17:15
source share

Looks for the glob () function:

 <?php $files = glob("dir/*.jpg"); foreach($files as $jpg){ echo $jpg, "\n"; } ?> 
+8
May 27 '11 at 17:13
source share

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 />"; } 
+3
May 27 '11 at 17:11
source share

Use the glob function in the foreach loop to make any option. I also used the file_exists function in the example below to check if the directory exists before moving on.

 $directory = 'my_directory/'; $extension = '.txt'; if ( file_exists($directory) ) { foreach ( glob($directory . '*' . $extension) as $file ) { echo $file; } } else { echo 'directory ' . $directory . ' doesn\'t exist!'; } 
+3
Oct. 15 '13 at 7:42 on
source share



All Articles