Format a file size
This example shows how to format a file and present its size better . If you use filesize on a file the size of the file in question is returned in bytes , this is fair enough when files are very small but what about when you have files that are measured in megabytes or gigabytes , unreadable .
This function will convert these into an easily readable format .
Code :
<?php
function format_size ($file)
{
//find the filesize of the file
$get_file_size = filesize($file);
//if the filesize has between 7 an 9 characters then its in Mb
if (strlen($get_file_size) <= 9 && strlen($get_file_size) >= 7)
{
$get_file_size = number_format($get_file_size / 1048576,1);
return "$get_file_size MB";
}
//10 characters or over means Gb
elseif (strlen($get_file_size) >= 10)
{
$get_file_size = number_format($get_file_size / 1073741824,1);
return "$get_file_size GB";
}
//anything else is kilobytes
else
{
$get_file_size = number_format($get_file_size / 1024,1);
return "$get_file_size KB";
}
}
?>
<?php
echo format_size("index.htm");
echo "<br>";
echo format_size("monthimages.zip");
echo "<br>";
echo format_size("sampledb.mdb");
?>
Example :
Warning: filesize() [function.filesize]: stat failed for index.htm in /home/beginne/public_html/formatsize.php on line 221
0.0 KB
128.8 KB
136.0 KB