php PHP脚本循环遍历目录中的所有文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4202175/
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 12:16:56  来源:igfitidea点击:

PHP script to loop through all of the files in a directory?

phpfile

提问by Moshe

I'm looking for a PHP script that loops through all of the files in a directory so I can do things with the filename, such as format, print or add it to a link. I'd like to be able to sort the files by name, type or by date created/added/modified. (Think fancy directory "index".) I'd also like to be able to add exclusions to the list of files, such as the script itself or other "system" files. (Like the .and .."directories".)

我正在寻找一个循环遍历目录中所有文件的 PHP 脚本,以便我可以对文件名进行处理,例如格式化、打印或将其添加到链接中。我希望能够按名称、类型或创建/添加/修改日期对文件进行排序。(想想花哨的目录“index”。)我还希望能够将排除项添加到文件列表中,例如脚本本身或其他“系统”文件。(就像...“目录”一样。)

Being that I'd like to be able to modify the script, I'm more interested in looking at the PHP docs and learning how to write one myself. That said, if there are any existing scripts, tutorials and whatnot, please let me know.

因为我希望能够修改脚本,所以我对查看 PHP 文档和学习如何自己编写一个更感兴趣。也就是说,如果有任何现有的脚本、教程等等,请告诉我。

回答by Morfildur

You can use the DirectoryIterator. Example from php Manual:

您可以使用DirectoryIterator。来自 php 手册的示例:

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
    }
}
?>

回答by NexusRex

If you don't have access to DirectoryIterator class try this:

如果您无权访问 DirectoryIterator 类,请尝试以下操作:

<?php
$path = "/path/to/files";

if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

        // do something with the file
    }
    closedir($handle);
}
?>

回答by ChorData

Use the scandir()function:

使用scandir()函数:

<?php
    $directory = '/path/to/files';

    if (!is_dir($directory)) {
        exit('Invalid diretory path');
    }

    $files = array();
    foreach (scandir($directory) as $file) {
        if ($file !== '.' && $file !== '..') {
            $files[] = $file;
        }
    }

    var_dump($files);
?>

回答by Julian

You can also make use of FilesystemIterator. It requires even less code then DirectoryIterator, and automatically removes .and ...

您还可以利用FilesystemIterator. 它需要更少的代码DirectoryIterator,并自动删除...

// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');

$entries = array();
foreach ($fileSystemIterator as $fileInfo){
    $entries[] = $fileInfo->getFilename();
}

var_dump($entries);

//OUTPUT
object(FilesystemIterator)[1]

array (size=14)
  0 => string 'aa[1].jpg' (length=9)
  1 => string 'Chrysanthemum.jpg' (length=17)
  2 => string 'Desert.jpg' (length=10)
  3 => string 'giphy_billclinton_sad.gif' (length=25)
  4 => string 'giphy_shut_your.gif' (length=19)
  5 => string 'Hydrangeas.jpg' (length=14)
  6 => string 'Jellyfish.jpg' (length=13)
  7 => string 'Koala.jpg' (length=9)
  8 => string 'Lighthouse.jpg' (length=14)
  9 => string 'Penguins.jpg' (length=12)
  10 => string 'pnggrad16rgb.png' (length=16)
  11 => string 'pnggrad16rgba.png' (length=17)
  12 => string 'pnggradHDrgba.png' (length=17)
  13 => string 'Tulips.jpg' (length=10)

Link: http://php.net/manual/en/class.filesystemiterator.php

链接:http: //php.net/manual/en/class.filesystemiterator.php

回答by GameScripting

You can use this code to loop through a directory recursively:

您可以使用此代码递归遍历目录:

$path = "/home/myhome";
$rdi = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
foreach (new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST) as $file => $info) {
    echo $file."\n";
}

回答by Sz.

For completeness (since this seems to be a high-traffic page), let's not forget the good old dir()function:

为了完整起见(因为这似乎是一个高流量页面),我们不要忘记旧dir()功能

$entries = [];
$d = dir("/"); // dir to scan
while (false !== ($entry = $d->read())) { // mind the strict bool check!
    if ($entry[0] == '.') continue; // ignore anything starting with a dot
    $entries[] = $entry;
}
$d->close();
sort($entries); // or whatever desired

print_r($entries);

回答by bcosca

glob()has provisions for sorting and pattern matching. Since the return value is an array, you can do most of everything else you need.

glob()有排序和模式匹配的规定。由于返回值是一个数组,因此您可以完成大部分其他您需要的操作。