Support Forums
Size Converter - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: PHP The Hypertext Preprocessor (https://www.supportforums.net/forumdisplay.php?fid=21)
+---- Thread: Size Converter (/showthread.php?tid=2687)



Size Converter - zone - 11-08-2009

Credits and Source: http://www.roscripts.com/

Name: Size Converter
Description: Converts an amount of bytes into a more human-readable format. Also includes a function (split from the original function) which returns the metric prefix for a given "position".
Snippet:

PHP Code:
/**
 * Get the human-readable size for an amount of bytes
 * @param int  $size      : the number of bytes to be converted
 * @param int $precision  : number of decimal places to round to;
 *                          optional - defaults to 2
 * @param bool $long_name : whether or not the returned size tag should
 *                          be unabbreviated (ie "Gigabytes" or "GB");
 *                          optional - defaults to true
 * @param bool $real_size : whether or not to use the real (base 1024)
 *                          or commercial (base 1000) size;
 *                          optional - defaults to true
 * @return string         : the converted size
 */
function get_size($size,$precision=2,$long_name=true,$real_size=true) {
   
$base=$real_size?1024:1000;
   
$pos=0;
   while (
$size>$base) {
      
$size/=$base;
      
$pos++;
   }
   
$prefix=get_size_prefix($pos);
   
$size_name=$long_name?$prefix."bytes":$prefix[0].'B';
   return 
round($size,$precision).' '.ucfirst($size_name);
}
/**
 * @param int $pos : the distence along the metric scale relitive to 0
 * @return string  : the prefix
 */
function get_size_prefix($pos) {
   switch (
$pos) {
      case 
00: return "";
      case 
01: return "kilo";
      case 
02: return "mega";
      case 
03: return "giga";
      case 
04: return "tera";
      case 
05: return "peta";
      case 
06: return "exa";
      case 
07: return "zetta";
      case 
08: return "yotta";
      case 
09: return "xenna";
      case 
10: return "w-";
      case 
11: return "vendeka";
      case 
12: return "u-";
      default: return 
"?-";
   }



Thankyou for reading. Be happy always Smile