3

dirlist

dirlist
SYNOPSIS

dirlist($dir='.')

DESCRIPTION

dirlist returns an array containing the names of all the files which are in the directory $dir and all its subdirectories. dirlist searches the current directory by default.

If $dir isn't a directory, dirlist returns false.

CODE
  1. function dirlist($dir='.') {
  2.     if (!is_dir($dir)) {
  3.         return false;
  4.     }
  5.  
  6.     $files = array();
  7.     dirlistaux($dir, $files);
  8.  
  9.     return $files;
  10. }

$dirlist initializes $dir with the name of the current directory by default, returns false if $dir isn't a directory, calls the auxiliary function $dirlistaux with the name of the directory to search and an empty array. $dirlist returns the array filled by $dirlistaux.

  1. function dirlistaux($dir, &$files) {
  2.     $handle = opendir($dir);
  3.     while (($file = readdir($handle)) !== false) {
  4.         if ($file == '.' || $file == '..') {
  5.             continue;
  6.         }
  7.         $filepath = $dir == '.' ? $file : $dir . DIRECTORY_SEPARATOR . $file;
  8.         if (is_link($filepath))
  9.             continue;
  10.         if (is_file($filepath))
  11.             $files[] = $filepath;
  12.         else if (is_dir($filepath))
  13.             dirlistaux($filepath, $files);
  14.     }
  15.     closedir($handle);
  16. }

$dirlistaux fills the array $files with the names of the all the files in the directory $dir and all its subdirectories. Note that $dir is passed by reference. $dirlistaux reads the directory $dir file by file, skips the file if it's the directory itself or its parent or a link, adds the file name to $files if it's a regular file, calls itself recursively with the file name in argument if it's a directory.

SEE ALSO

dirclear, dircopy

Comments

To add a comment, click here.