Directory files scanner with sorting.
Posted: Wed Apr 04, 2007 10:27 am
I ought to make this into an object or something really.
To use it just call getFiles() and then uasort() the returned array. Eg:
Change the second argument in uasort to one of the six functions I've given to change the sorting, eg sortby_date_asc, sortby_date_desc, sortby_name_asc, sortby_name_desc, sortby_size_asc, sortby_size_desc.
Comments appreciated.
Code: Select all
function getFiles($path,$level=0) {
static $arrIgnoreDirectories = array("directory1","directory2");
static $arrIgnoreFiles = array("topSecretFile.txt");
static $arrAllowedExtensions = array("php","txt");
if (is_dir($path)) {
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
$fullpath = $path."/".$file;
if ($file == "." || $file == "..") continue;
if ((in_array($file,$arrIgnoreDirectories) and is_dir($fullpath)) or (in_array($file,$arrIgnoreFiles) and !is_dir($fullpath))) continue;
if (!in_array(fileExtension($file),$arrAllowedExtensions) and !is_dir($fullpath)) continue;
$a = stat($fullpath);
$files[$fullpath]['size'] = (is_dir($fullpath)) ? 0 : $a['size'];
$files[$fullpath]['name'] = $file;
$files[$fullpath]['type'] = filetype($fullpath);
$files[$fullpath]['hash'] = (is_dir($fullpath)) ? "" : md5_file($fullpath);
$files[$fullpath]['mtime'] = $a['mtime'];
$files[$fullpath]['level'] = $level;
if (is_dir($fullpath)) {
getFiles($fullpath,$level+1);
}
}
closedir($dh);
}
}
return $files;
}
function fileExtension($file) {
return substr($file,strrpos($file,".")+1);
}
function sortby_date_asc($ar1, $ar2) {
if ($ar1['mtime']<$ar2['mtime']) { return -1; } elseif ($ar1['mtime']>$ar2['mtime']) { return 1; }
return 0;
}
function sortby_date_desc($ar1, $ar2) {
if ($ar1['mtime']<$ar2['mtime']) { return 1; } elseif ($ar1['mtime']>$ar2['mtime']) { return -1; }
return 0;
}
function sortby_name_asc($ar1, $ar2) {
if ($ar1['name']<$ar2['name']) { return -1; } elseif ($ar1['name']>$ar2['name']) { return 1; }
return 0;
}
function sortby_name_desc($ar1, $ar2) {
if ($ar1['name']<$ar2['name']) { return 1; } elseif ($ar1['name']>$ar2['name']) { return -1; }
return 0;
}
function sortby_size_asc($ar1, $ar2) {
if ($ar1['size']<$ar2['size']) { return -1; } elseif ($ar1['size']>$ar2['size']) { return 1; }
return 0;
}
function sortby_size_desc($ar1, $ar2) {
if ($ar1['size']<$ar2['size']) { return 1; } elseif ($ar1['size']>$ar2['size']) { return -1; }
return 0;
}Code: Select all
$files = getFiles("myDirectory");
foreach($files as $file => $data) {
echo $data['name']." - ".date("d/m/Y H:i:s",$data['mtime'])."<br>";
}
echo "<br><br>";
uasort($files, 'sortby_date_asc');
foreach($files as $file => $data) {
echo $data['name']." - ".date("d/m/Y H:i:s",$data['mtime'])."<br>";
}
Comments appreciated.