Friendly file size for a file using php code

Hi friends, In this post i would like to explain about get the friendly file size using simple php code.

PHP Code

following code is very simple to get the friendly file size format using php code.

function frndlyfilesize($filesize){

$decr = 1024;
$step = 0;
$prefix = array('Byte','KB','MB','GB','TB','PB');

while(($fileName / $decr) > 0.9){
$filesize = $filesize / $decr;
return round($filesize,2).' '.$prefix[$step];
} else {

return 'Nothing';


To call that function :

$ filesize = filesize("test.jpg");
$newSize = frndlyfilesize($filesize);


Expected output like the format :


5 MB  or 5 KB or 5 GB ……

Anil Kumar Panigrahi

With more than 10 years experience in PHP and Founder of Anil Labs, a blog for PHP and related posts. contributed posts regarding CodeIgniter, CakePHP and Learn PHP online ... Contact : [email protected]

You may also like...

1 Response

  1. Ruel says:

    I think it should be
    while(($filesize / $decr) > 0.9)

    and NOT
    while(($fileName / $decr) > 0.9)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.