note 100710 modified in function.readdir by danbrown

From: Date: Mon, 01 Nov 2010 15:51:35 +0000
Subject: note 100710 modified in function.readdir by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-173671@lists.php.net to get a copy of this message
A variation on listing all the files in a directory recursively. The code illustrates a basic technique : the use of an auxiliary function. It avoids building temporary lists which are merged on the way back. Note that the array which collects the information must be passed by reference. <?php function listdir($dir='.') { if (!is_dir($dir)) { return false; } $files = array(); listdiraux($dir, $files); return $files; } function listdiraux($dir, &$files) { $handle = opendir($dir); while (($file = readdir($handle)) !== false) { if ($file == '.' || $file == '..') { continue; } $filepath = $dir == '.' ? $file : $dir . '/' . $file; if (is_link($filepath)) continue; if (is_file($filepath)) $files[] = $filepath; else if (is_dir($filepath)) listdiraux($filepath, $files); } closedir($handle); } $files = listdir('.'); sort($files, SORT_LOCALE_STRING); foreach ($files as $f) { echo $f, "\n"; } ?> --was-- A variation on listing all the files in a directory recursively. The code illustrates a basic technique : the use of an auxiliary function. It avoids building temporary lists which are merged on the way back. Note that the array which collects the information must be passed by reference. function listdir($dir='.') { if (!is_dir($dir)) { return false; } $files = array(); listdiraux($dir, $files); return $files; } function listdiraux($dir, &$files) { $handle = opendir($dir); while (($file = readdir($handle)) !== false) { if ($file == '.' || $file == '..') { continue; } $filepath = $dir == '.' ? $file : $dir . '/' . $file; if (is_link($filepath)) continue; if (is_file($filepath)) $files[] = $filepath; else if (is_dir($filepath)) listdiraux($filepath, $files); } closedir($handle); } $files = listdir('.'); sort($files, SORT_LOCALE_STRING); foreach ($files as $f) { echo $f, "\n"; } http://php.net/manual/en/function.readdir.php

« previous php.notes (#173671) next »