我正在尝试使用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()方法都要快。
答案 0 :(得分:10)
SELF_FIRST
和CHILD_FIRST
与RecursiveDirectoryIterator
毫无关系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
你能看到当前文件夹的位置差异