I'm trying to build a <ul>
list with a <li>
for each directory in a main folder.
here's my code :
<?php
$dir = opendir(getEnv("DOCUMENT_ROOT") . "/folder");
while(($file = readdir($dir)) !== false ){
if( is_dir($file) && $file !== "." && $file !== ".." ){
echo "<li>" . $file . "</li>";
}
}
closedir($dir);
?>
there are two directories in /home/example/folder but there are not recognized as folders (for sure they ar开发者_如何学JAVAe !)
if I "echo
" the files in the while loop they are printed (they well exist for the script no trouble on that side).
If I try to "filetype
" them, a lstat failed
error is thrown, I searched on internet the meaning of it and I end up with nothing but technically support that I pain to understand.
Your problem is that inside "folder" directory you can have two directories (a and b),then the reading retrieve "a" and "b" as file names, while is_dir receive a full path filename or a relative filename, you have two options:
- pass the full path to filename to the is_dir function (see example code).
- pass the relative path (depends on where you put your script).
if( is_dir($dir . "/" . $file) && $file !== "." && $file !== ".." ){ ......
Try:
while($file = readdir($dir)) {
if (...) { }
}
The !== false
portion is not required. if readdir reaches the end, it returns a false, and the loop will automatically terminate. Your version is being parsed as:
$file gets the value of (readdir($file) is not false)
e.g. you're assigning the boolean result of readdir($file) !== false
, not the return value from readdir.
to expand on my comment below, regarding operator precedence:
PHP's parse tree of your loop setup looks like this, expanded:
$bool = (readdir($dir) !== false);
$file = $bool;
To fix this, either remove the !== false portion entirely, or enforce your own precedence with extra brackets:
($file = readdir($dir)) !== false
精彩评论