Page 362 - Beginning PHP 5.3
P. 362

Part III: Using PHP in Practice
                How It Works
                The traverseDir() recursive function traverses the whole directory hierarchy under a specified
                directory. First, the function displays the path of the directory it is currently exploring. Then, it opens
                the directory with opendir():

                      if ( !( $handle = opendir( $dir ) ) ) die( “Cannot open $dir.” );

                Next the function sets up a $files array to hold the list of filenames within the directory, then uses
                readdir() with a while loop to move through each entry in the directory, adding each filename to
                the array as it goes (”.” and “..” are skipped). If a particular filename is a directory, a slash (/) is
                added to the end of the filename to indicate to the user (and the rest of the function) that the file is in
                fact a directory:

                      $files = array();

                      while ( $file = readdir( $handle ) ) {
                        if ( $file != “.” && $file != “..” ) {
                          if ( is_dir( $dir . “/” . $file ) ) $file .= “/“;
                          $files[] = $file;
                        }
                      }
                Now the array of filenames is sorted alphabetically to aid readability, and the filenames are displayed
                in an unordered list:

                      sort( $files );
                      echo “<ul>“;
                      foreach ( $files as $file ) echo “<li>$file</li>“;
                      echo “</ul>“;

                The last part of the function loops through the array again, looking for any directories (where the
                filename ends in a slash). If it finds a directory, the function calls itself with the directory path (minus
                the trailing slash) to explore the contents of the directory:
                      foreach ( $files as $file ) {
                        if ( substr( $file, -1 )  == “/” ) traverseDir( “$dir/” . substr( $file,
                    0, -1 ) );
                      }
                Finally, the directory handle is closed:
                      closedir( $handle );

                The last line of code in the script kicks off the directory traversal, starting with the path to the initial,
                topmost directory:
                    traverseDir( $dirPath );









              324





                                                                                                      9/21/09   9:10:20 AM
          c11.indd   324                                                                              9/21/09   9:10:20 AM
          c11.indd   324
   357   358   359   360   361   362   363   364   365   366   367