php - 目录中每个文件的循环代码

这个问题在这里已有答案:

  • 获取目录中的文件                                     3个答案

我有一个图片目录,我想循环并做一些文件计算。 它可能只是缺乏睡眠,但我如何使用PHP查看给定目录,并使用某种for循环遍历每个文件?

谢谢!

Chiggins asked 2019-08-13T21:59:18Z
5个解决方案
240 votes

SCANDIR:

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

或者glob可能更适合您的需求:

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}
Emil Vikström answered 2019-08-13T21:59:38Z
56 votes

查看DirectoryIterator类。

从该页面上的一条评论:

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

递归版本是RecursiveDirectoryIterator。

squirrel answered 2019-08-13T22:00:15Z
8 votes

寻找函数glob():

<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
    echo $jpg, "\n";
}
?>
fvox answered 2019-08-13T22:00:39Z
3 votes

试试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 />";  
}  
Phill Pafford answered 2019-08-13T22:01:02Z
2 votes

在foreach循环中使用glob函数来执行任何选项。 我还使用了下面示例中的file_exists函数来检查目录是否存在,然后再继续。

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

if ( file_exists($directory) ) {
   foreach ( glob($directory . '*' . $extension) as $file ) {
      echo $file;
   }
}
else {
   echo 'directory ' . $directory . ' doesn't exist!';
}
Jake answered 2019-08-13T22:01:27Z
translate from https://stackoverflow.com:/questions/6155533/loop-code-for-each-file-in-a-directory