【问题标题】:building a simple directory browser using php RecursiveDirectoryIterator使用 php RecursiveDirectoryIterator 构建一个简单的目录浏览器
【发布时间】:2011-09-07 13:52:49
【问题描述】:

嗨 我正在尝试构建简单的目录浏览器来使用 php RecursiveDirectoryIterator 浏览文件夹和子文件夹。我需要有关如何创建它的帮助。我从以下代码开始。

$dir = dirname(__FILE__); //path of the directory to read
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as  $file) {
if (!$file->isFile()) { //create hyperlink if this is a folder
echo "<a href=". $file->getPath().">" . $file->getFilename() . "\</a>";
}else{ //do not link if this is a file
  $file->getFilename()
  }
}

【问题讨论】:

    标签: php browser directory


    【解决方案1】:

    请允许我为您编写代码......

    <?php
    $root = __DIR__;
    
    function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
        $directory = realpath($directory);
        $parent = realpath($file);
        $i = 0;
        while ($parent) {
            if ($directory == $parent) return true;
            if ($parent == dirname($parent) || !$recursive) break;
            $parent = dirname($parent);
        }
        return false;
    }
    
    $path = null;
    if (isset($_GET['file'])) {
        $path = $_GET['file'];
        if (!is_in_dir($_GET['file'], $root)) {
            $path = null;
        } else {
            $path = '/'.$path;
        }
    }
    
    if (is_file($root.$path)) {
        readfile($root.$path);
        return;
    }
    
    if ($path) echo '<a href="?file='.urlencode(substr(dirname($root.$path), strlen($root) + 1)).'">..</a><br />';
    foreach (glob($root.$path.'/*') as $file) {
        $file = realpath($file);
        $link = substr($file, strlen($root) + 1);
        echo '<a href="?file='.urlencode($link).'">'.basename($file).'</a><br />';
    }
    

    【讨论】:

    • 谢谢 Petah...您给定的代码工作正常...我们可以改进此代码...就像我想根据修改时间对文件和文件夹进行排序???/跨度>
    • @chinto,随心所欲。
    • 如何排除php、html等扩展名,能否添加
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    相关资源
    最近更新 更多