php - 使用递归目录迭代器

标签 php

<分区>

Possible Duplicate:
Displaying folders and making links of those folders

我正在尝试使用 RecursiveDirectoryIterator 创建一个简单的文件浏览器,但似乎无法弄清楚......请帮忙吗?

$cwd = '/path/to/somewhere';
if(isset($_GET['path']) && is_dir($cwd.$_GET['path'])) {
    $cwd .= $_GET['path'];
}

$dir = new RecursiveDirectoryIterator($cwd);
$iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
while($iter->valid()) {
    // skip unwanted directories
    if(!$iter->isDot()) {
        if($iter->isDir()) {
            // output linked directory along with the number of files contained within
            // for example: some_folder (13)
        } else {
            // output direct link to file
        }
    }
    $iter->next();
}

不确定这是否是最佳方法,但我的印象是 RecursiveDirectoryIterator 比 opendir() 和 glob() 方法都快。

最佳答案

SELF_FIRSTCHILD_FIRSTRecursiveDirectoryIterator 无关,但与 RecursiveIteratorIterator

无关

如果你跑

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );

foreach ( $iterator as $path ) {
    if ($path->isDir()) {
        print($path->__toString() . PHP_EOL);
    } else {
        print($path->__toString() . PHP_EOL);
    }

你会得到

...\htdocs\lab\stockoverflow\css
...\htdocs\lab\stockoverflow\css\a.css
...\htdocs\lab\stockoverflow\css\b.css
...\htdocs\lab\stockoverflow\css\c.css
...\htdocs\lab\stockoverflow\css\css.php
...\htdocs\lab\stockoverflow\css\css.run.php

如果将其更改为 RecursiveIteratorIterator::CHILD_FIRST

...\htdocs\lab\stockoverflow\css\a.css
...\htdocs\lab\stockoverflow\css\b.css
...\htdocs\lab\stockoverflow\css\c.css
...\htdocs\lab\stockoverflow\css\css.php
...\htdocs\lab\stockoverflow\css\css.run.php
...\htdocs\lab\stockoverflow\css

你能看出区别在于当前文件夹的位置吗

关于php - 使用递归目录迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12661885/

相关文章:

php - 在 php 数组中将结果整数除以 1000

php - 从 PHP 中的字符串中检测语言

php - 使用 Button OnClickListener 将 JSON 响应加载到 Listview

php - 从复选框查询

php - 如何执行PHPUnit?

php - APC 是否与 PHP 5.4 或 PHP 5.5 兼容?

php - 如何从数据库中提取数据以制作常见问题解答页面?

php - 我的评论系统不会将内容添加到我的数据库中

php - 这个 AS3 代码与 PHP 文件通信有什么问题?

php - 如何在 cakephp 中创建带有联接的查询