Page 1 of 1

is_dir

Posted: Sat May 25, 2002 1:29 pm
by wertzb
I am having trouble understanding howi s_dir() function operates. I am using a while loop to read the content of a directory. In my output I only want to display directories, not files. The following code does not work. It prints the filenames also.

Code: Select all

$rootDirName = "Topics"; // set the top level folder
$rootDir = opendir($rootDirName); 
// step through each folder (skip files) stored in $rootDir 
while ($rootFolder = readdir($rootDir))
{
     if (is_dir($rootFolder) ) {
          print ...;
    }
} // end while
I had to include the directory one level up from the one I am reading to get the is_dir() function to work. This works. It skips files and prints directories.

Code: Select all

$rootDirName = "Topics"; // set the top level folder
$rootDir = opendir($rootDirName); 
// step through each folder (skip files) stored in $rootDir 
while ($rootFolder = readdir($rootDir))
{
     $folder = $rootDirName . "&quote; . $rootFolder; 		
     if (is_dir($folder) ) {
          print ...;
     }
} // end while
Can anyone explain why?

Posted: Sat May 25, 2002 5:03 pm
by volka
think about the name of the function is_dir
if $rootFolder is a directory print its name
But you want: if $rootFolder is not a directory print its name

Code: Select all

if (!is_dir($rootFolder) ) { 
   print ...;

Posted: Tue May 28, 2002 2:32 pm
by wertzb
I want to skip filenames and only process directories or folders.

Posted: Tue May 28, 2002 2:48 pm
by volka
you're right, sorry (my second excuse today - something's wrong ;) )

readdir returns the names as seen relative from the directory that has been opened.
if you have a directory /<path>/Topic/Topic1 and open the directory '/<path>/Topic' readdir will return 'Topic1' not '/<path>/Topic/Topic1'.
Your readdir then is the same as is_dir('./Topic1'). If your script resides somewhere else and there is no subdir 'Topic1' in the script-directory it returns FALSE (and the other way round).