note 71480 deleted from function.scandir by danbrown
| From: | danbrown@php.net | Date: | Thu, 28 Jan 2010 14:16:14 +0000 |
| Subject: | note 71480 deleted from function.scandir by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-165448@lists.php.net to get a copy of this message | ||
Note Submitter: SkyEye
----
dirlst - function to get directory and subdirectory file listing. Function outputs
an array with filenames and optionally also their mod.time and/or size.
You can choose also whether to include subdirectory names into listing
Function returns number of files listed.
$srcdir - source directory (without ending slash)
$fs - output array
$p - position of relative path, usually $p = strlen($srcdir) + 1;
set to 0 to store absolute path
$getfmt - set to 1 to include filemodtime in output
$getfsz - set to 1 to include filesize in output
$getdrs - set to 1 to include subdirectory names in output
$verbose - set to 1 to display output in runtime
Usage example.
Get directory listing (files only) and save it into a file:
<?php
$srcdir = 'C:\SomeFolder';
dirlst($srcdir, $files, strlen($srcdir) + 1, 1, 1, 0, 0);
file_put_contents($filename, join("", $files));
?>
Get listing from file and explode contents:
<?php
$files = file($fn);
foreach($files as $line) {
list($file,$fmt,$fsz)=explode('|',$line);
//...
}
?>
[Function:]
<?php
function dirlst($srcdir, &$fs, $p=0, $getfmt=0, $getfsz=0, $getdrs=0, $verbose=0) {
$num = 0;
if(($files = scandir($srcdir))!==false) {
foreach($files as $file) {
if($file != '.' && $file != '..') {
$srcfile = $srcdir . '\\' . $file;
$sf = substr($srcfile,$p);
$sst = stat($srcfile);
if($getfmt) { $fmt = $sst['mtime']; $sf.='|'.$fmt; }
if($getfsz) { $fsz = $sst['size']; $sf.='|'.$fsz; }
if(is_file($srcfile)) {
$fs[] = $sf."|\n";
if($verbose) echo $sf."|\n";
}
else if(is_dir($srcfile)) {
if($getdrs) { $fs[] = $sf."|\n"; if($verbose) echo $sf."|\n"; }
$num += dirlst($srcfile, $fs, $p, $getfmt, $getfsz, $getdrs, $verbose);
}
}
}
}
return $num;
}
?>
dirsort - function to sort directory listing array. Function returns sorted array.
$fs - sortable array (got by dirlst())
$col - column to sort; if the listing contains filename, filemodtime and filesize,
then: 0 - files, 1 - mod.time, 2 - size
$dsc - set to 0 to sort ascending, 1 - to sort descending
Usage example.
Sort by size, ascending:
$fs = dirsort($fs, 2, 0);
<?php
function dirsort($fs, $col=0, $dsc=0) {
foreach($fs as $line) list($col0[],$col1[],$col2[]) = explode('|',$line);
if($col==0) {
natcasesort($col0); if($dsc) $col0=array_reverse($col0,1);
$keys = array_keys($col0);
}
if($col==1) {
if($dsc) arsort($col1); else asort($col1);
$keys = array_keys($col1);
}
if($col==2) {
if($dsc) arsort($col2); else asort($col2);
$keys = array_keys($col2);
}
foreach($keys as $k) $nfs[] = $fs[$k];
return $nfs;
}
?>