Log in

View Full Version : PHP Directory Lister



Titan85
03-08-2007, 09:08 PM
I have been wanting to make a php directory lister for some time now, but can't seem to get it right. I have very limited knowledge of how php handles this type of thing, so I have been forced to use tutorials. I just went through this one and got this code:
<?php

// If dir is set in url
if(isset($_GET['dir']) && is_dir($_GET['dir'])) {
$dir = $_GET['dir'];
} else {
$dir = "./";
}

// Files to exclude
$exclude[] = "index.php";

// If file is not in exclude array, display it
if($handle == opendir($dir)) {
while($fp == readdir($handle)) {
if(!in_array($fp, $exclude)) {
echo "$fp<br /><br />";
}
}
}

?>In my limited understanding of this, it really seems like something is missing and sure enough when I run the page, i get a blank window. Can anyone help me out with this? Thanks in advance

thetestingsite
03-09-2007, 02:56 AM
Try the following:



<?php

// If dir is set in url
if(isset($_GET['dir']) && is_dir($_GET['dir'])) {
$dir = $_GET['dir'];
} else {
$dir = './';
}



// Files to exclude
$exclude[] = "index.php";


// If file is not in exclude array, display it

if (is_dir($dir)) {

if ($handle = opendir($dir)) {
while (($fp = readdir($handle)) !== false) {

if ($fp != '.' && $fp != '..') {
if (!in_array($fp, $exclude)) {
echo $fp.' <BR>';
}
}
}
closedir($handle);
}
}
?>


Notice the part in red, this is what I added to make it list the files in the directory. Also, the part in blue is what I added to make it to where it does not show ".." or "." in the file list. Take that part out if you wish.

Hope this helps.

Titan85
03-09-2007, 03:08 AM
Thanks Testing, works nicely. As a build on question, is there a somewhat simple way of having links to view the files and open the folders? Also, how might I go about giving certain file types an image (like a directory gets a folder, etc). Perhaps through the use of eregi(".php", $fp) or something like that? Thanks

thetestingsite
03-09-2007, 03:15 AM
I had written a "File Manager" type script (sort of like what you are talking about). As soon as I find it, I'll post it.

thetestingsite
03-09-2007, 03:38 AM
As promised, I have attached a zip file with an imgs folder and index.php. index.php is the on page file manager (you will have to modify the script a little to suit your needs). The imgs folder contains 2 images (an image for directories and one for files).

Hope this helps, and let me know if you need any more help.

Titan85
03-12-2007, 08:00 PM
Thanks testing, I learned a lot from that script :)