PHP traverses the directory and returns the statistical directory size

  • 2021-06-28 11:59:34
  • OfStack

 
<?php 
$dirname = "test1"; 
//mkdir($dirname); 

// ergodic 1 Layer directory  
function listdir($dirname) { 
$ds = opendir($dirname); 
while($file = readdir($ds)) { 
$path = $dirname.'/'.$file; 
if(is_dir($file)) { 
echo "DIR:".$file."<br>"; 
if($file != "." && $file != "..") { 
listdir($file); 
} 
} 
else { 
echo "FILE:".$file . "<br>"; 
} 
} 
} 

function totdir($dirname) { // Yes listdir make a few alterations  
static $tot = 0; 
$ds = opendir($dirname); 
while($file = readdir($ds)) { 
$path = $dirname.'/'.$file; 
if(is_dir($file)) { 
//echo "DIR:".$file."<br>"; 
if($file != "." && $file != "..") { 
$tot += totdir($file); 
} 
} 
else { 
//echo "FILE:".$file . "<br>"; 
$tot += filesize($path); 
} 
} 

// Return Total  
return $tot; 
} 

listdir($dirname); 

echo totdir($dirname)." bytes"; 

?> 

Related articles: