I have a directory of pictures that I want to loop through and do some file calculations on. It might just be lack of slee开发者_如何转开发p, but how would I use PHP to look in a given directory, and loop through each file using some sort of for loop?
Thanks!
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
}
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.
Looks for the function glob():
<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
echo $jpg, "\n";
}
?>
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 />";
}
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!';
}
精彩评论