How to Format Raw Byte File Size into a Humanly Readable Value Using PHP

Nothing like spending a beautiful Fall Saturday morning programming, that is the story of my life. I am finally getting close to completing VoiceTales. One of the last steps in the project to create a simple function that shows a humanly readable file size value for each recording a customer makes. I looked around and found a few suggestions online. I have combined a couple of useful strategies to create the following PHP function designed to automatically convert a byte value into the corresponding MB, GB, TB, etc. value. Once complete the function returns the value for use within a script or for output. Check out the function and good luck using it on your project:

<?PHP
    /**********************************************
    //FORMAT RAW SIZE FOR FRIENDLY DISPLAY
   ***********************************************/			
    function formatRawSize($bytes) {
 
        //CHECK TO MAKE SURE A NUMBER WAS SENT
        if(!empty($bytes)) {
 
            //SET TEXT TITLES TO SHOW AT EACH LEVEL
            $s = array('bytes', 'kb', 'MB', 'GB', 'TB', 'PB');
            $e = floor(log($bytes)/log(1024));
 
            //CREATE COMPLETED OUTPUT
            $output = sprintf('%.2f '.$s[$e], ($bytes/pow(1024, floor($e))));
 
            //SEND OUTPUT TO BROWSER
            return $output;
 
        }
   }
?>

No related posts.

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

Nice helpful script, and far simpler than my attempt. Cheers!

Hi Tom

Great function, thanks for sharing.

I have extended it slightly.

Say for example the raw input in bytes is ’755′. This currently displays as ’755.00 bytes’. As you can see, the ‘.00′ isn’t really helpful in the ‘bytes’ size category. The following function removes the ‘.00′ for ‘bytes’, but keeps it for the remaining categories:

sprintf(‘%.’ . ($e == 0 ? 0 : 2) . ‘f ‘.$s[$e], etc

Cheers from South Africa,
KK

Is there any reason to use floor($e) as $e is already returned as a floor’d number a couple of lines up.

Leave a comment

(required)

(required)