PHP Statistic Directory Size Custom Function Sharing

  • 2021-08-03 09:35:16
  • OfStack

Calculating the size of files, disk partitions, and directories is a common task in various applications. The file size can be calculated using the filesize () function described earlier, and the disk size can be calculated using the disk_free_space () and disk_total_space () functions. However, PHP does not provide a standard function for the total directory size at present, so we need to customize one function to complete this task. First of all, consider whether the calculated directory contains other subdirectories. If there are no subdirectories, the sum of the sizes of all files in the directory is the size of this directory. If subdirectories are included, calculate the size of the subdirectory by 1 again according to this method. Using recursive functions seems to be the most suitable task for this task. The custom function to calculate the directory size is as follows:


<?php
// Customize 1 Functions dirSize() Statistics the directory size of the incoming parameters
function dirSize($directory){
  $dir_size = 0; // Used to accumulate individual file sizes
 
  if($dir_handle = @opendir($directory)){      // Open the directory and determine whether it was successfully opened
    while($filename = readdir($dir_handle)){     // Loop through all the files in the directory
        if($filename != "."&& $filename != ".."){     //1 Be sure to exclude two special directories
            $subFile = $directory."/".$filename;     // Connect the subfiles in the directory with the current directory
            if(is_dir($subFile))     // If it is a directory
            $dir_size += dirSize($subFile);     // Call its own function recursively to find the size of subdirectories
            if(is_file($subFile))     // If it is a file
            $dir_size += filesize($subFile);     // Find the file size and accumulate it
        }
    }
    closedir($dir_handle);      // Close file resources
    return $dir_size;     // Returns the calculated directory size
  }
}
 
$dir_size = dirSize("phpMyAdmin");    // Call this function to calculate the directory size
echo round($dir_size/pow(1024,1),2)."KB";    // The number of bytes is converted to " KB "Unit and output
?>

You can also use the exec () or system () function to call the operating system command "du" to return the directory size. However, for security reasons, these functions are usually disabled and are not conducive to cross-platform operation.


Related articles: