The base calculation is 1024 because 1kb is 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 code, we use a mathematical PHP function called pow()
, which makes potential expression calculations.
Important, in this example returns the result formatted with 2 decimal places.
The formatting of the result may vary with the need of each one. Therefore, be aware and modify according to your need.
More specifically, referring to your code, remove all unnecessary chunk:
// 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];
Trade for 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);
It is also important to point out that it is somewhat unwise to say so, regarding Kib and KB. Despite the existence of the IEC standard, there is nothing wrong with presenting KB as "Kilobyte", which is also presented as only "K", informally in the technological world. What’s more, by the JEDEC standard, kb is 1024. In practice, the IEC standard on the subject is useless and ignored by industry, except for Apple’s OS-X operating system. Anyway, this is a subject somewhat outside the scope of the question. Of course it’s interesting, but I think there should be a specific topic for such a discussion.
– Daniel Omine
Reckless is using a unit where people can misinterpret, JEDEC warns about this: The Specification Notes that These prefixes are included in the Document only to reflect common Usage. It refers to the IEEE/ASTM SI 10-1997 standard as stating, that "this Practice Frequently leads to Confusion and is deprecated".
– Alexandre Borela
Jesuis.........
– Daniel Omine
Ask for 10 people without knowledge in T.I. and 10 others who are beginners in programming to convert Byte to Kbyte... Kib was created to avoid these confusions. As to be useless in the industry, just look that not all HD manufacturers use base 1024 (it has been some years that I do not see Hdds using this base, I myself have a 120GB Kingston SSD which is ~111GiB).
– Alexandre Borela
sasinhora......
– Daniel Omine