Format bytes with PHP – B, KB, MB, GB, TB, PB, EB, ZB, YB converter

php-logo

Simple PHP function that formats the bytes to the desired form. Possible unit options are:

  • Byte (B)
  • Kilobyte (KB)
  • Megabyte (MB)
  • Gigabyte (GB)
  • Terabyte (TB)
  • Petabyte (PB)
  • Exabyte (EB)
  • Zettabyte (ZB)
  • Yottabyte (YB)

Function takes three parameter: (bytes mandatory, unit optional, decimals optional)

PHP byteFormat function for formatting bytes

Example usage

Prints

Share this post

10 Comments

  1. Raaaddddd!
    Thanks dude. Saved me a bunch of time.

    I used this for formating bytes, btw:

    /**
    * filesize function.
    *
    * @access public
    * @static
    * @param mixed $size
    * @param int $round. (default: 0)
    * @return void
    */
    // http://www.veign.com/code-view.php?type=web&codeid=74
    public static function filesize($size, $round = 0) {
    $sizes = array(‘b’, ‘kb’, ‘meg’, ‘gb’, ‘tb’, ‘pb’, ‘eb’, ‘zb’, ‘yb’);
    for ($i=0; $size > 1024 && isset($sizes[$i+1]); $i++) $size /= 1024;
    return round($size, $round).$sizes[$i];
    }

    Reply
  2. Thanks.

    Reply
    • Dr Garg? How strange that I should find your name on a random website. I guess we were both looking for the same kind of info. :)

      Reply
  3. not much helpful…..

    Reply
  4. Amazing!!, but in the examples, consider remove the \n concat, because the example becomes difficult to read… greetings from Argentina.

    Reply
    • Hi Juan,

      Thanks, I removed \n from examples and yes, you are right, it’s easier to read.

      Reply
  5. Thanks man, very helpful function, i implemented it in my template engine.

    Thanks again

    Reply
  6. Thanks, I owe you one.

    Reply
  7. nice

    Reply

Trackbacks/Pingbacks

  1. Egonomik » PHP – Byte dönüştürme fonksiyonu (Convert bytes) - [...] "n"; echo byteFormat(1099511627776, "PB", 6) . "n";Kaynak: if-not-true-then-false.com Düzenleme için Umut‘a teÅŸekkürler. Benzer YazılarPHP – Resim üzerine yazı yazma …

Submit a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">