2011-06-03 131 views
0

嗨 我想构建简单的目录浏览器浏览文件夹和子文件夹uing php RecursiveDirectoryIterator ..我需要帮助如何创建此。我已经开始使用下面的代码。建立一个简单的目录浏览器使用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

什么是你确切的问题? – cweiske 2011-06-03 05:37:26

回答

19

允许我的代码,你....

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

谢谢佩塔...你给定的代码工作正常...我们可以改进这个代码...就像我想在修改时间的基础上排序文件和文件夹???/ – mubashir 2011-06-03 07:22:14

+7

@chinto,做任何你想要的用它。 – Petah 2011-06-03 11:13:14

+0

如何排除像PHP,HTML等扩展名,请你可以添加 – 2015-05-08 11:26:08