您好 我正在尝试构建简单的目录浏览器来浏览文件夹和子文件夹uing 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()
}
}
答案 0 :(得分:20)
请允许我为你编码......
<?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 />';
}