普通网友 2012-10-03 05:50
浏览 31
已采纳

优化文件导航器

I've come up with a basic file navigator that accepts user input to jump to different directories. The only problem I have with it is that I'm basically looping over the data three times:

  1. Get a valid list of all directories for comparison against user input
  2. Build a "sorted" list of directories and files
  3. Output final list

Any tips on optimizing or improving this code?

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 />";
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dtjo87679 2012-10-03 16:14
    关注

    How often is the directory structure going to change? Can it be cached and the whitelist be re-generated only when there are changes instead of on each request? This would be my approach depending on requirements and load factors.Beyond that probably lies the realm of micro-optimizations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号