我想出了一个基本的文件导航器,它接受用户输入以跳转到不同的目录。我遇到的唯一问题是我基本上循环了数据三遍:
- 获取所有目录的有效列表,以便与用户输入进行比较
- 构建目录和文件的“排序”列表
- 输出最终列表
有关优化或改进此代码的任何提示?
define('ROOT', '/path/to/somewhere');
// get a list of valid paths
$valid = array();
$dir = new RecursiveDirectoryIterator(ROOT);
$dir->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$iter = new ParentIterator($dir);
foreach(new RecursiveIteratorIterator($iter, RecursiveIteratorIterator::SELF_FIRST) as $file) {
$path = str_replace(ROOT, '', $file->getPathname());
$valid[] = $path;
}
// user input
$subpath = isset($_GET['path']) && in_array($_GET['path'], $valid) ? $_GET['path'] : NULL;
$cwd = isset($subpath) ? ROOT.$subpath : ROOT;
// build and sort directory tree
$files = array();
foreach(new DirectoryIterator($cwd) as $file) {
if($file->isDot()) {
continue;
}
if($file->isDir()) {
$path = str_replace(ROOT, '', $file->getPathname());
$count = iterator_count(new RecursiveDirectoryIterator($file->getRealPath(), FilesystemIterator::SKIP_DOTS));
$files[$path]['name'] = $file->getFilename();
$files[$path]['count'] = $count;
} else {
$files[] = $file->getFilename();
}
asort($files);
}
// output directory tree
if(!empty($files)) {
foreach($files as $key=>$value) {
if(is_array($value)) {
echo "<a href=\"?path=$key\">{$value['name']} ({$value['count']})</a><br />";
} else {
echo "$value<br />";
}
}
}