我想出了一个基本的文件导航器,它接受用户输入来跳转到不同的目录。我唯一的问题是我基本上循环数据三次:
有关优化或改进此代码的任何提示吗?
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 />";
}
}
}
答案 0 :(得分:0)
目录结构多久会改变一次?它是否可以缓存,只有在有变化而不是每个请求时才重新生成白名单?这将是我的方法,取决于要求和负载因素。可能是微优化的领域。