Jun
3
Quick PHP Function to Get File Sizes in KB, MB & GB
Posted by john in no category

Here’s the follow-up article on how to easily get file sizes nicely formated. 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
echo formatbytes("$_SERVER[DOCUMENT_ROOT]/images/large_picture.jpg", "MB");
// would display the file size in MB

Just remember the file location has to be the absolute location on the server. It can not be relative (’/images/….’) Please let me know if you have any questions about any of this.

Leave a Reply