-->

how do I exclude non-folders files from this readd

2019-09-19 07:40发布

问题:

The following lists the folders, the index.php and the favicon.ico in the directory. I want to see only folders.

Any ideas?

Thanks.

   <?php
     // opens this directory
     $myDirectory = opendir(".");

     // gets each entry
     while($entryName = readdir($myDirectory)) {
       $dirArray[] = $entryName;
     }

     // closes directory
     closedir($myDirectory);

     //  counts elements in array
     $indexCount   = count($dirArray);

     // sorts files
     sort($dirArray);

     // print 'em
     print("<table width='100%' cellspacing='10'>
             <tr>
               </tr>\n");

     // loops through the array of files and print them all
     for($index=0; $index < $indexCount; $index++) {
           if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
           print("<tr><td><a href='$dirArray[$index]'>$dirArray[$index]</a></td>");
           print("</tr>\n");
       }
     }
     print("</table>\n");
   ?>

回答1:

Use the following:

 // gets each entry
 while($entryName = readdir($myDirectory)) {
   if(is_dir($entryName)) {
     $dirArray[] = $entryName;
   }
 }

I however suggest to use glob() for this kind of operation. e.g.:

glob($dir . '/*', GLOB_ONLYDIR)


标签: php readdir