Met de volgende snippets kun je bytes converteren naar leesbare tekst en vice versa.
De eerste snippet bytes_to_human converteert bytes naar tekst.
8589934592 => 8 GB
De tweede snippet human_to_bytes converteert tekst naar bytes.
4 GB => 4294967296
/**
* bytes_to_human()
*
* this function converts bytes to a human readable format
*
* @param mixed $size Size in bytes
* @return string human readable size
*/
if(!function_exists('bytes_to_human'))
{
function bytes_to_human($size)
{
if (preg_match('/^([0-9\.]+)\s*([KMGTPEZY]B)$/i', $size))
{
return $size;
}
else if(!is_numeric($size))
{
return '';
}
else if($size < 0)
{
$negative = '- ';
$size = abs($size);
}
else
{
$negative = '';
}
$names = array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
return $size ? $negative.round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) .' '.$names[$i] : '0 Bytes';
}
}
// --------------------------------------------------------------------
/**
* human_to_bytes
*
* this function converts human readable size to bytes
*
* @param mixed $size Size
* @return int size in bytes
*/
if(!function_exists('human_to_bytes'))
{
function human_to_bytes($size)
{
$bytes = 0;
$matches = array();
$size = str_replace(',' ,'.', $size); //eliminate comma's
if(is_numeric($size))
{
$bytes = $size;
}
else if (preg_match('/^([0-9\.]+)\s*([KMGTPEZY])?(B(ytes)?)?$/i', $size, $matches))
{
$size = $matches[1];
$orders = array("K", "M", "G", "T", "P", "E", "Z", "Y");
$order = array_search(strtoupper($matches[2]), $orders);
if($order === FALSE)
{
$bytes = $size; // Assume bytes
}
else
{
$multiplier = pow(2, ($order + 1) * 10);
$bytes = $size * $multiplier;
}
}
return $bytes;
}
}