Generate Readable Byte Labels Using PHP

By  on  

Whenever you manage disk space, it's infinitely easier to read when when the bytes are displayed in KB, MB, GB... format. When reading files on the disk, the server returns the disk space in bytes so it's on us programmers to program file sizes for display. Using PHP, this task is cake.

function format_bytes($bytes)
{
    $labels = array('B','KB','MB','GB','TB');
    for($x = 0; $bytes >= 1024 && $x < (count($labels) - 1); $bytes /= 1024, $x++);
    return(round($bytes, 2).' '.$labels[$x]);
}

Users will appreciate this!

Recent Features

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

Incredible Demos

  • By
    Link Nudging with CSS3 Animations

    One of the more popular and simple effects I've featured on this blog over the past year has been linking nudging.  I've created this effect with three flavors of JavaScript:  MooTools, jQuery, and even the Dojo Toolkit.  Luckily CSS3 (almost) allows us to ditch...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Discussion

  1. JP

    I always like using the right-shift operator for this kind of stuff. So instead of:

    $bytes /= 1024

    I would use:

    $bytes >>= 10

    Of course, you lost the digits after the decimal point (unless you get fancy), but on the plus side, it’s way faster than floating point division. The shift operators must be some of the loneliest operators in PHP, don’t you think?

  2. Nice one!
    I did a similar function … somewhat overkill, but a usefull thing over the years =)
    http://openminds.lucido-media.de/human-readable-bytes-sorry-php-net

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!