is_dir not working as expected
Solution 1
As Kolink said in the comments, you're probably better off going the glob
route, but if you decide to stick with opendir:
The path will be $folder . '/' . $file, not just $file. opendir() returns relative paths. So is_dir is returning false in your loop.
if ($dir = opendir($folder)){
while(false !== ($file = readdir($dir))) {
if ($file == '.' || $file == '..') {
continue;
} else if (is_dir($folder . '/' . $file)) {
$files[] = $file;
}
}
closedir($dir);
}
Also, note the false !==
. This is necessary because a folder named "0" would evaluate to false (or a few other edge cases). Also, you'll very rarely actually care about .
and ..
, so that code is in there to filter .
and ..
out.
Solution 2
Problem is: $file contains only the basename, not the absolute filename. So prepend the path to the folder:
is_dir($folder . '/' . $file)
Related videos on Youtube
LuthorMithos
Updated on June 04, 2022Comments
-
LuthorMithos about 2 years
I've got a problem when using is_dir while I iterate over all the files in a certain directory. The code is kind of small so I think you'll better understand what I mean if I post it:
$files = array(); if ($dir = @opendir($folder)){ while($file = readdir($dir)){ if (is_dir($file)) $files[] = $file; } closedir($dir); } print_r($files)
It dumps: ( [0] => . )
Otherwise, if I don't check wether the file is a dir by using this code:
$files = array(); if ($dir = @opendir($folder)){ while($file = readdir($dir)){ $files[] = $file; } closedir($dir); } print_r($files)
It dumps what expected: ( [0] => .. [1] => bla [2] => blablabla [3] =>index.php [4] => styles.css [5] => . )
I guess it's just some noob problem with using the $file var as a parameter but don't know how to make it work.
Thanks for reading!
-
Admin about 12 yearsdo you just want a list of all the subdirectories? if so use glob()
-
Niet the Dark Absol about 12 yearsYou appear to be reinventing the wheel for
glob("*",GLOB_ONLYDIR)
. If this is the case, problem has already been solved ;) -
LuthorMithos about 12 yearsOks, problem solved, thanks to you guys, this was pretty fast, Didn't know about this glob option nor the relative path of opendir. Thanks!!
-
Marc B about 12 years
.
and..
are special directories that appear automatically in EVERY directory..
= current directory,..
= parent directory. Unless you filter them out, they'll always show up in opendir/readdir. -
Rajan Rawal about 12 yearsthe is_dir function wants complete file/dir path as argument. Check that what you get in the $file. If you are getting only file name then you prepend the parent directory path
-
-
LuthorMithos about 12 yearsThanks you too for answering. Already solved it, as I said in the first comment.