Smiley Happy Coder

Lyle Barras

Lyle is Smiley Happy Coder

Developing for the web since 1999, that's 17 years

Simple way to humanise files sizes in PHP

This is just a very quick post to show something I’ve just been working on.

I came upon the need to display file sizes in a human readable way. The PHP method FILESIZE returns the size of the file in bytes. You might see a file size of 1500 or even 23462966. Now what do that mean to the average user? Nothing, so lets humanise it.

The function to humanise files sizes

private function humaniseBytes($bytes , $precision = 2)
    //Get the length of the string
    $length = strlen($bytes);

    if ($length <= 3){
        return $bytes . 'B';
    } elseif( $length > 3 && $length < 7){
        return number_format($bytes / 1000 , $precision) . 'KB';
    } elseif( $length > 6 && $length <10 ){
        return number_format($bytes / 1000000 , $precision) . 'MB';
    } elseif ( $length > 9 && $length < 13){
        return number_format($bytes / 1000000000 , $precision) . 'GB';
    } elseif ( $length > 12){
        return number_format($bytes / 1000000000000 , $precision) . 'TB';

The first thing you’ll note are the parameters passed, obviously the $bytes are passes as well as a variable called $precision. This variable just determines the decimal places that should be returned from the number_format function.

I then just simple loop through and find the length and divide by whatever I need to in order to move the decimal place correctly.

Some functions you might see calculate based on the actual file size, my method however uses the string length. Now I will say that this might not be the most accurate solution since a KB isn’t actually 1000 bytes but rather 1024 bytes.

I hope this helps someone out there.

Share me...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInBuffer this pagePin on PinterestEmail this to someone
  • Top

Read all my posts