Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Return a Readable Filesize with PHP

PHP's filesize() function will do as described: get the size of a file in bytes. However, it's usually necessary to convert that returned value into something more readable, and the PHP functions in this article will accomplish that.

The first function will take a value in bytes and return a human readable string. The B for bytes, K for kilobytes, M for megabytes, etc will be appended, and the decimal value will be truncated to your specified length.

1
<?php 
2
<?php
3
/*
4
 Return a Readable Filesize with PHP
5
 http://www.beliefmedia.com/readable-filesize-php
6
*/
7
 
8
function beliefmedia_filesize($bytes, $decimals = 2) {
9
  $sz = 'BKMGTP';
10
  $factor = floor((strlen($bytes) - 1) / 3);
11
  return sprintf(&quot;%.{$decimals}f&quot;, $bytes / pow(1024, $factor)) . @$sz[$factor];
12
}
13
 
14
/* Usage */
15
$bytes = '70652868';
16
echo beliefmedia_filesize($bytes, $decimals = 2);
17
?>

It's often necessary to include the filesize() functionality into the actual function. The second function will take a file path as an argument and return the human readable size of the referenced file.

1
<?php 
2
<?php
3
/*
4
 Return a Readable Filesize with PHP
5
 http://www.beliefmedia.com/readable-filesize-php
6
*/
7
 
8
function beliefmedia_file_size($path, $decimals = 2) {
9
  $bytes = filesize($path);
10
  $sz = 'BKMGTP';
11
  $factor = floor((strlen($bytes) - 1) / 3);
12
  return sprintf(&quot;%.{$decimals}f&quot;, $bytes / pow(1024, $factor)) . @$sz[$factor];
13
}
14
 
15
/* Usage */
16
$path = '/home/user/public_html/dir/file.jpg';
17
echo beliefmedia_file_size($path, $decimals = 2);
18
?>

If you're looking to return the size of an entire directory, you'll find that article here (when published).

Download


Title: Return a Readable Filesize with PHP
Description: Return a readable filesize with PHP. Two functions: single value, and path to a file.
  Download • Version 0.2, 536.0B, zip, Category: PHP Code & Snippets

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Connecticut)

  Want to have a chat?
 

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433

NOPE