Reputation: 159
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!
Upvotes: 3
Views: 21119
Reputation: 1
<? // findfiles.php - what is in directory "videoarchive"
$dir = 'images/videoarchive/'; // path from top
$files = scandir($dir);
$files_n = count($files);
echo '<br>There are '.$files_n.' records in directory '.$dir.'<br>' ;
$i=0;
while($i<=$files_n){
// "is_dir" only works from top directory, so append the $dir before the file
if (is_dir($dir.'/'.$files[$i])){
$MyFileType[$i] = "D" ; // D for Directory
} else{
$MyFileType[$i] = "F" ; // F for File
}
// print itemNo, itemType(D/F) and itemname
echo '<br>'.$i.'. '. $MyFileType[$i].'. ' .$files[$i] ;
$i++;
}
?>
Upvotes: 0
Reputation: 33457
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.
Upvotes: 6
Reputation: 26730
Problem is: $file contains only the basename, not the absolute filename. So prepend the path to the folder:
is_dir($folder . '/' . $file)
Upvotes: 3