Filter Sub-Directories for Output Using php

When I needed a quick solution to output a sub-directories list to web page I was a little lost.  My web projects are almost always database driven. Projects that rely more on the retrieval of data from a database then traversing a directory.  In the past I had used the opendir() function, something like this stack overflow answer.  This seemed a little clunky and I figured there was a better solution. A little research soon showed a better solution. The solution I settled on made use of php’s glob and in_array functions.

 

File structure of the directory I am outputting.
CubePro directory structure screenshot
CubePro directory structure screenshot
The results:
Results of filtering out subdirectory for output

The solution to outputting sub-directories using php:

<?php
     // array or subdirectories to exclude from output
      $exceptionList = array("node_modules", "include", "SuiteCRM-7.7.4", "kaz", "admin", "moreltees.com"););
     // get array of subdirectories
      $directory = array_filter(glob('*'), 'is_dir');
     //output
      foreach($directory as $directoryName) {
          // compare directory name to see if it exists in the exception list
           if (!in_array($directoryName, $exceptionList)) {
                echo "<h3><a href='".$directoryName."'>".$directoryName."</a></h3>";
           } 
      }
 ?>

Leave a Reply