-
Nov 14th, 2010, 11:34 AM
#1
Thread Starter
Frenzied Member
[RESOLVED] Directories not being detected
Hello, I wrote a simple script to display all the files/folders in a directory. When you click a file it will open the file. When you click a directory it SHOULD list all the files/folders in that directory.
Here is my script:
PHP Code:
<?php $html=""; $dir='.'; if(isset($_GET['dir'])){ if(strlen($_GET['dir']) > 0){ $dir = $_GET['dir']; } } if ($handle = opendir($dir)) { $html .= "<table style='border: 1px solid black;'>"; while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { if(!is_dir($file)){ $html .= "<tr><td><a href='".$dir.'/'.$file."'>$file</a></td></tr>"; } else{ $html .= "<tr><td><a href='index.php?dir=".$dir.'/'.$file."'>$file</a></td></tr>"; } } } $html .= "</table>"; closedir($handle); } echo $html; ?>
Don't just correct the code, please provide an explanation so I don't repeat this error in the future.
-
Nov 14th, 2010, 12:42 PM
#2
Re: Directories not being detected
the problem is you're checking if $file is a directory -- $file, after progressing to a new directory, is just the name of the file we're on, rather than the file's path. for ease, I've modified your code and highlighted what I've changed to make is_dir() check the file's path. also, I fixed any pathing issues you would have had (missing trailing slashes after progressing to a directory, etc).
Code:
<?php
$html="";
$dir='./';
if(isset($_GET['dir'])){
if(strlen($_GET['dir']) > 0){
$dir = $_GET['dir'];
}
}
if ($handle = opendir($dir)) {
$html .= "<table style='border: 1px solid black;'>";
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(!is_dir($dir . $file)){
$html .= "<tr><td><a href='" . $dir . $file . "'>$file</a></td></tr>";
}
else{
$html .= "<tr><td><a href='index.php?dir=" . $dir . $file . "/'>/$file/</a></td></tr>";
}
}
}
$html .= "</table>";
closedir($handle);
}
echo $html;
?>
-
Nov 14th, 2010, 01:02 PM
#3
Thread Starter
Frenzied Member
Re: Directories not being detected
Thank you.
I knew it was a pathing issue, I even tried to add $dir to the is_dir parameters but I guess I was missing the other changes.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|