PHP 列出指定目录下的所有文件的几种方法

Php 2020-04-27 阅读 439 评论 0

下面列举使用 PHP,实现遍历指定文件夹下所有文件的几种方法。

1. DirectoryIterator

使用 DirectoryIterator 目录接口。使用 isDot() 方法确定当前项是 . 还是 ..

$dir = '/develop';
foreach (new DirectoryIterator($dir) as $file) {
    if ($file->isDot()) {
        continue;
    }
    echo $file->getFilename() . PHP_EOL;
}

2. FilesystemIterator

参考 FilesystemIterator 文件系统迭代器。

foreach (new FilesystemIterator("/develop") as $file) {
    echo $file->getFilename(), PHP_EOL;
}

3. scandir

参考文档 scandir,列出指定路径中的文件和目录。

$files = scandir('/develop');
foreach ($files as $file) {
    if (in_array($file, ['.', '..'])) {
        continue;
    }
    echo $file . PHP_EOL;
}

4. opendir 和 readdir

参考 opendirreaddir 。打开目录句柄,并从目录句柄中读取条目。

if ($handle = opendir('/develop')) {
    while (false !== ($file = readdir($handle))) {
        if (in_array($file, ['.', '..'])) {
            continue;
        }
        echo $file . PHP_EOL;
    }
    closedir($handle);
}

5. glob

参考 glob。寻找与模式匹配的文件路径。

glob 很不错,使用星符号 * ,可以对文件进行匹配, glob('*.txt') 将列出当前路径下的所有 .txt 文本, glob('image_*') 可以显示以 image_ 开头的文件。但是需要注意的是,* 不会匹配点号开头的隐藏文件。

foreach (glob("/develop/*") as $file) {
    if (in_array($file, ['.', '..'])) {
        continue;
    }
    echo $file . PHP_EOL;
}
最后更新 2020-04-27