Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert KB MB GB TB etc to Bytes


I'm asking how to convert KB MB GB TB & co. into bytes.
For example:

byteconvert("10KB") // => 10240
byteconvert("10.5KB") // => 10752
byteconvert("1GB") // => 1073741824
byteconvert("1TB") // => 1099511627776

and so on...

EDIT: wow. I've asked this question over 4 years ago. Thise kind of things really show you how much you've improved over time!

like image 564
user1494162 Avatar asked Aug 04 '12 08:08

user1494162


People also ask

How can convert MB to KB in PHP?

php $units = explode(' ','B KB MB GB TB PB'); echo("<html><body>"); echo('file size: ' . format_size(filesize("example. txt"))); echo("</body></html>"); function format_size($size) { $mod = 1024; for ($i = 0; $size > $mod; $i++) { $size /= $mod; } $endIndex = strpos($size, ".")+3; return substr( $size, 0, $endIndex).

What is B KB MB GB TB?

A kilobyte (KB) is 1,000 bytes, and one megabyte (MB) is 1,000 kilobytes. One gigabyte (GB) is equal to 1,000 megabytes, while a terabyte (TB) is 1,000 gigabytes.

How many KB is MB 1000 or 1024?

1 Megabyte is equal to 1000 kilobytes (decimal). 1 MB = 103 KB in base 10 (SI). 1 Megabyte is equal to 1024 kilobytes (binary).


2 Answers

Wanting something similar to this and not quite liking the other solutions posted here for various reasons, I decided to write my own function:

function ConvertUserStrToBytes($str)
{
    $str = trim($str);
    $num = (double)$str;
    if (strtoupper(substr($str, -1)) == "B")  $str = substr($str, 0, -1);
    switch (strtoupper(substr($str, -1)))
    {
        case "P":  $num *= 1024;
        case "T":  $num *= 1024;
        case "G":  $num *= 1024;
        case "M":  $num *= 1024;
        case "K":  $num *= 1024;
    }

    return $num;
}

It adapts a few of the ideas presented here by Al Jey (whitespace handling) and John V (switch-case) but without the regex, doesn't call pow(), lets switch-case do its thing when there aren't breaks, and can handle some weird user inputs (e.g. " 123 wonderful KB " results in 125952). I'm sure there is a more optimal solution that involves fewer instructions but the code would be less clean/readable.

like image 177
CubicleSoft Avatar answered Oct 20 '22 04:10

CubicleSoft


Based on https://stackoverflow.com/a/17364338/1041470

Improvements:

  • Fixed bug with bytes suffix length,
  • Allowed to use double (float) values but only integers,
  • Reverted array which holds units,
  • Renamed variables,
  • Added comments.
/**
 * Converts human readable file size into bytes.
 *
 * Note: This is 1024 based version which assumes that a 1 KB has 1024 bytes.
 * Based on https://stackoverflow.com/a/17364338/1041470
 *
 * @param string $from
 *   Required. Human readable size (file, memory or traffic).
 *   For example: '5Gb', '533Mb' and etc.
 *   Allowed integer and float values. Eg., 10.64GB.
 *
 * @return int
 *   Returns given size in bytes.
 */
function cm_common_convert_to_bytes(string $from): ?int {
  static $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  $from = trim(check_plain($from));
  // Get suffix.
  $suffix = strtoupper(trim(substr($from, -2)));
  // Check one char suffix 'B'.
  if (intval($suffix) !== 0) {
    $suffix = 'B';
  }
  if (!in_array($suffix, $units)) {
    return FALSE;
  }
  $number = trim(substr($from, 0, strlen($from) - strlen($suffix)));
  if (!is_numeric($number)) {
    // Allow only float and integer. Strings produces '0' which is not corect.
    return FALSE;
  }
  return (int) ($number * pow(1024, array_flip($units)[$suffix]));
}
like image 33
VladSavitsky Avatar answered Oct 20 '22 04:10

VladSavitsky