7

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

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].