Artykuły na każdy temat
[PHP] Konwersja wielkości pliku
<?php
class converter
{
static private $units = ['B', 'kB', 'MB', 'GB', 'TB'];
static public function convert_to_readable_size($size)
{
$unit = floor(log($size, 1024));
return round($size / pow(1024, $unit), 2).' '.self::$units[$unit];
}
// Alternative way
// static public function convert_to_readable_size($size)
// {
// $unit = 0;
//
// while($size >= 1024)
// {
// $size /= 1024;
// ++$unit;
// }
//
// return round($size, 2).' '.self::$units[$unit];
// }
static public function convert($size, $unit, $decimals = 2)
{
$unit = array_search(strtolower($unit), array_map('strtolower', self::$units));
if($unit !== false)
{
$value = $size / pow(1024, $unit);
return sprintf('%.'.$decimals.'f '.self::$units[$unit], $value);
}
}
static public function convert_to_bytes($size)
{
preg_match('#(\d+(?:[\.|\,]{1}\d+)?)\s*([k|m|g|t]?b){1}#i', $size, $matches);
if(count($matches) > 0)
{
$matches[1] = str_replace(',', '.', $matches[1]);
$factor = array_search(strtolower($matches[2]), array_map('strtolower', self::$units));
if($factor !== false)
{
return round(((float)$matches[1] * pow(1024, $factor)), 2);
}
}
}
}
?>
Szybkie testy:
<?php
require './converter.class.php';
// Tests
// echo converter::convert_to_readable_size(1024);
// echo converter::convert_to_bytes('1024 kB');
// echo converter::convert(1024, 'MB', 4);
?>
Komentarze
Dodaj komentarz