RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Return a Readable Filesize with PHP

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.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment