« Return to Blog

PHP Practical Solutions: File System

Author: Zeeshan Arshad     321     05/23/2014

Estimated reading time: 0 minutes, 36 seconds

Recursive all files and count usage space


[codesyntax lang="php"]


$ite=new RecursiveDirectoryIterator("files/");

$bytestotal=0;
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
$filesize=$cur->getSize();
$bytestotal+=$filesize;
$nbfiles++;
echo "$filename => $filesize
";
}

$bytestotal=number_format($bytestotal);
echo "Total: $nbfiles files, $bytestotal bytesn";
?>


[/codesyntax]

Convert a Nested Directory Tree into a Multidimensional Array


[codesyntax lang="php"]


$ritit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($startpath), RecursiveIteratorIterator::CHILD_FIRST); 
$r = array();
foreach ($ritit as $splFileInfo) {
$path = $splFileInfo->isDir()
? array($splFileInfo->getFilename() => array())
: array($splFileInfo->getFilename());

for ($depth = $ritit->getDepth() - 1; $depth >= 0; $depth--) {
$path = array($ritit->getSubIterator($depth)->current()->getFilename() => $path);
}
$r = array_merge_recursive($r, $path);
}

print_r($r);
?>


[/codesyntax]