Basic PHP Function to Get File Sizes in KB, MB & GB
June 3, 2008 • 1 min read
Here’s the follow-up article on how to easily get file sizes nicely formatted. Below is a quick function that will display the file size in KB, MB, or GB all easily accessed through a function.
function formatbytes($file, $type)
{
switch($type) {
case "KB":
$filesize = filesize($file) * .0009765625; // bytes to KB
break;
case "MB":
$filesize = (filesize($file) * .0009765625) * .0009765625; // bytes to MB
break;
case "GB":
$filesize = ((filesize($file) * .0009765625) * .0009765625) * .0009765625; // bytes to GB
break;
}
if($filesize <= 0){
return $filesize = 'unknown file size';}
else{return round($filesize, 2).' '.$type;}
}
Usage
// display the file size in MB
echo formatbytes("$_SERVER[DOCUMENT_ROOT]/images/large_picture.jpg", "MB");
Just remember the file location has to be the absolute location on the server – it can not be relative