0

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()
  }
}
Mubashir
  • 567
  • 3
  • 8
  • 25

1 Answers1

20

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 />';
}
Petah
  • 45,477
  • 28
  • 157
  • 213
  • Thanks Petah...Your given code is working fine...can we improve this code...like i want to sort files and folder on the basis of modified time ???/ – Mubashir Jun 03 '11 at 07:22
  • 7
    @chinto, do what ever you want with it. – Petah Jun 03 '11 at 11:13
  • how to exclude extensions like php, html and so please, can you please add –  May 08 '15 at 11:26