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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6155533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:30:39  来源:igfitidea点击:

Loop code for each file in a directory

phpimagefilesystemsdirectory

提问by Chiggins

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?

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

Thanks!

谢谢!

回答by Emil Vikstr?m

scandir:

扫描目录

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

or globmay be even better for your needs:

glob可能更适合您的需求:

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

回答by squirrel

Check out the DirectoryIteratorclass.

查看DirectoryIterator类。

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.

递归版本是RecursiveDirectoryIterator

回答by fvox

Looks for the function glob():

查找函数glob()

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

回答by Phill Pafford

Try GLOB()

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

回答by Jake

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.

在 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!';
}