使用 php RecursiveDirectoryIterator 构建一个简单的目录浏览器 [英] building a simple directory browser using php RecursiveDirectoryIterator

查看:29
本文介绍了使用 php RecursiveDirectoryIterator 构建一个简单的目录浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi i am trying to build simple directory browser to browse folders and sub-folders uing php RecursiveDirectoryIterator .. i need help of how to create this. i have started with the following code.

$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()
  }
}

推荐答案

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

Allow me to code that for you....

<?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 />';
}

这篇关于使用 php RecursiveDirectoryIterator 构建一个简单的目录浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆