May 092012

I found this on the php API website a long time ago. It’s been useful a few times. I’d love to give credit to the original creator, but I have no idea who that might be at this point.

Returns the file size unit, i.e. B, KB, MB, GB of a file size. $size is the file size in Bytes

function filesize_format ($size) {

	// Make sure variable is integer.
	$size *= 1;

	// An array of file size units.
	$units = array('B', 'KB', 'MB', 'GB');

	// This filters out (by dividing) the value until it reaches
	// within the byte value (0-1023) or runs out of known units.
	// How many times it iterates tells the unit.
	for ($i = 0; $size >= 1023 && $i < sizeof($units); $i++) { 

		$size /= 1024;

	return number_format($size, 1) . ' ' . $units[$i];

 Posted by at 12:01 am