A function to get file sizes in multiple formats with curl.


/ Published in: PHP
Save to your folder(s)

A function to get a files size via curl. Accepts $_path, $_unit, $_float, $_username & $_password; In the listed order.


Copy this code and paste it in your HTML
  1. function file_size($_path, $_unit, $_float = null, $_username = null, $_password = null) {
  2. $_unit = trim(strtoupper($_unit)); //Making the unit compatible
  3. function unit_size($data, $_unit, $_float) {
  4. if (!isset($_float)) {$_float = 3;} // float 3 decimal places by default
  5. $sizes = array("B"=>0, "KB"=>1, "MB"=>2, "GB"=>3, "TB"=>4, "PB"=>5, "EB"=>6, "ZB"=>7, "YB"=>8); //Associated with each unit is the exponent that will be used to do the conversion from bytes
  6. if (array_key_exists($_unit, $sizes) && $sizes[$_unit] != 0) { // If the unit is not bytes we get down to business
  7. $number = $sizes[$_unit];
  8. $total = $data / (pow(1024, $number));
  9. return round($total, $_float)." ".$_unit;
  10. }
  11. else {return $data." B";} // If you want bytes then we just skip to this part
  12. }
  13. $ch = curl_init($_path);
  14. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  15. curl_setopt($ch, CURLOPT_HEADER, TRUE);
  16. if(isset($userame) && isset($password)) { $headers = array('Authorization: Basic '.base64_encode("$user:$pw")); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); }
  17. curl_setopt($ch, CURLOPT_NOBODY, TRUE);
  18. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  19. curl_setopt($ch, CURLOPT_URL, $_path); //specify the ur
  20. $data = curl_exec($ch);
  21. $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
  22. curl_close($ch);
  23. return unit_size($size, $_unit, $_float);
  24. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.