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
- function dirlist($dir='.') {
- if (!is_dir($dir)) {
- return false;
- }
- $files = array();
- dirlistaux($dir, $files);
- return $files;
- }
$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
.
- function dirlistaux($dir, &$files) {
- $handle = opendir($dir);
- while (($file = readdir($handle)) !== false) {
- if ($file == '.' || $file == '..') {
- continue;
- }
- $filepath = $dir == '.' ? $file : $dir . DIRECTORY_SEPARATOR . $file;
- if (is_link($filepath))
- continue;
- if (is_file($filepath))
- $files[] = $filepath;
- else if (is_dir($filepath))
- dirlistaux($filepath, $files);
- }
- closedir($handle);
- }
$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.
Comments