Posted By

MMDeveloper on 12/29/09


Tagged

filesize file size calculate


Versions (?)

Calculate and return filesize of file in different units of measurement


 / Published in: PHP
 

URL: http://skyward.nefec.org

Simply pass the path to the file, the desired units of measurement, decimal rounding, and separator. For example, a 1024kb file (1mb)

$filesizeStats = getFilesize("path/to/file.jpg", "kb", 2, " ");
print_r($filesizeStats);

//will return

array (
        "rawBytes" => 131072,
        "convertedSize" => 1024.00,
        "convertedSize_formatted" => "1,024.00",
        "units" => "kb",
        "formatted" => "1,024.00 kb"
    )
  1. /**
  2. * This method calculates, converts, and reports filesize information
  3. * @access public
  4. * @author Matt Ford
  5. * @param string $file absolute path to a file
  6. * @param string $units abbreviation of units to report formatted size in, defaults to kb
  7. * @param integer $rounding number of decimal places to round to, defaults to 2
  8. * @param string $seperator string seperator to place between in the formatted output between the numerical size and the units, defaults to one space
  9. * @return array array of filesize information along with units and a per-formatted string output
  10. */
  11. public function getFilesize($file, $units = "kb", $rounding = 2, $seperator = " ") {
  12. $return = array ("size" => "FnF");
  13. $lcUnits = strtolower($units);
  14.  
  15. if (file_exists($file)) {
  16. $fileSize = filesize($file);
  17.  
  18. if (!$fileSize) {
  19. $returnSize = "err";
  20. }
  21. else {
  22. switch ($lcUnits) {
  23. case "bits":
  24. $returnSize = $fileSize * 8;
  25. break;
  26.  
  27. default:
  28. case "b":
  29. $returnSize = $fileSize;
  30. $units = "b";
  31. break;
  32.  
  33. case "kb":
  34. $returnSize = $fileSize / 1024;
  35. break;
  36.  
  37. case "mb":
  38. $returnSize = $fileSize / 1048576;
  39. break;
  40.  
  41. case "gb":
  42. $returnSize = $fileSize / 1073741824;
  43. break;
  44.  
  45. case "tb":
  46. $returnSize = $fileSize / 1099511627776;
  47. break;
  48. }
  49.  
  50. $returnSize_formatted = number_format($returnSize, $rounding, ".", ",");
  51. }
  52. }
  53. else {
  54. $returnSize = "FnF";
  55. }
  56.  
  57. $return = array (
  58. "rawBytes" => $fileSize,
  59. "convertedSize" => $returnSize,
  60. "convertedSize_formatted" => $returnSize_formatted,
  61. "units" => $units,
  62. "formatted" => $returnSize_formatted . $seperator . $units
  63. );
  64.  
  65. return $return;
  66. }

Report this snippet  

You need to login to post a comment.