Search code examples
phpfile-typescandir

is_dir() fails while scanning a directory in php


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 are !)

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.


Solution

  • 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:

    1. pass the full path to filename to the is_dir function (see example code).
    2. pass the relative path (depends on where you put your script).
    if( is_dir($dir . "/" . $file) && $file !== "." && $file !== ".." ){ ......