[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.
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;
?>
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.