The basis of calculation is 1024 because 1kb is equivalent to 1024 bytes.
Based on this, create a function that determines the type of measure.
/*
1024000 bytes = 1 kilobytes
1000 kb = 1 megabyte
1000 mb = 1 gigabyte
e assim vai..
*/
function filesize_formatted($path)
{
$size = filesize($path);
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$power = $size > 0 ? floor(log($size, 1024)) : 0;
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
echo filesize_formatted( 2048 );
In this example, in order to reduce the code, we use a PHP math function called pow()
, which makes potential expression calculations.
Important, in this example returns the result formatted to 2 decimal places.
The formatting of the result may vary with the need for each. So be aware and modify as needed.
Being more specific about your code, remove all unnecessary snippets:
// Pega o tamanho do arquivo remoto
$tamanhoarquivo = $filesize;
//
$medidas = array('KB', 'MB', 'GB', 'TB');
/* Se for menor que 1KB arredonda para 1KB */
if($tamanhoarquivo < 999){
$tamanhoarquivo = 1024;
}
for ($i = 0; $tamanhoarquivo > 999; $i++){
$tamanhoarquivo /= 1024;
}
return round($tamanhoarquivo) . $medidas[$i - 1];
Switch to this:
function filesize_formatted($path)
{
$size = filesize($path);
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$power = $size > 0 ? floor(log($size, 1024)) : 0;
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
return filesize_formatted( $filesize);