Scandir on steroids:
For when you want to filter your file list, or only want to list so many levels of subdirectories...
<?php
function dirList($path="", $types=2, $levels=1, $aFilter=array()) {
$dS = DIRECTORY_SEPARATOR;
if (!($path = realpath($path?$path:getcwd()))) return array(); if (substr($path,-1)==$dS) $path = substr($path,0,-1);
if (is_null($types)) $types = 2;
if (is_null($levels)) $levels = 1;
if (is_null($aFilter)) $aFilter=array();
$aFilter = array_slice(func_get_args(),3);
if ($aFilter && gettype($aFilter[0])=="array") $aFilter=$aFilter[0];
$adFilter = array();
foreach ($aFilter as $i=>$filter) if (($pos=stripos(" $filter","d")) && $pos<3) { $adFilter[] = substr($filter,0,$pos-1) . substr($filter,$pos);
unset($aFilter[$i]); }
$aFilter = array_merge($aFilter); $aRes = array(); $aDir = array($path); for ($i=$levels>0?$levels++:-1;($aAcc=array())||$i--&&$aDir;$aDir=$aAcc)
while ($dir = array_shift($aDir))
foreach (scandir ($dir) as $fileOrDir)
if ($fileOrDir!="." && $fileOrDir!="..") {
if ($dirP = is_dir ($rp="$dir$dS$fileOrDir"))
if (pathFilter("$rp$dS", $adFilter))
$aAcc[] = $rp;
if ($i<$levels-1 && ($types & (2-$dirP)))
if (pathFilter($rp, $aFilter))
$aRes[] = ($dirP?"*":"") . $rp; }
return $aRes;
}
?>
example usage:
<?php
define ("_", NULL);
$aFiles = dirList('c:\Photo', _, 0, '-/\.jpg$/i', '-/\\\\Thumbs.db$/');
$aFiles = dirList(); set_time_limit(60); $aFiles = dirList("c:\\", _, 0, '/\.jpg$/i', '-d/\\\\Photos?$/i', '-d/Temporary Internet/i');
?>
Note that this function will consume a lot of time if scanning large
directory structures (which is the reason for the '[-]d/.../' filters).
Csaba Gabor from Vienna