Page 1 of 1

PHP Convert Bytes to Readable KB

Posted: Thu Jun 14, 2018 3:02 am
by MrCambron
PHP Convert Bytes to Readable KB.

I am not exactly sure how I ended up with this code. But I can tell that some of it is my scripting. If I did some copy and paste then sure I would give credits if I find out where I got it. Because I really don't know how I can think of something like that, I am pretty sure my script would be different.

Code: Select all

<?php
echo hRBC(1234567, 0); // print in KB

function hRBC($bytes, $si) {
  // phpflare.com
  $unit = ($si) ? 1000 : 1024;
  $pb = "KMGTPE";
  if ($bytes < $unit) return $bytes." B";
  (int)$expf = floor(log($bytes) / log($unit));
  $pre = $pb[(int)$expf-1].($si ? "" : "i");
  return sprintf("%.1f %sB", $bytes / pow($unit, $expf), $pre);
}
?>