Simple PHP function to convert numbers in bytes to nice kb, mb, gb etc…



Hi, this is a nice function maybe useful for your coding need in PHP.

This function will convert any numbers in bytes to a nice format like kb, mb, gb and so on.

Here we go:

function formatFileSize($bytes){
	if ($bytes >= 1073741824)
	{
		$bytes = number_format($bytes / 1073741824, 2) . ' GB';
	}
	elseif ($bytes >= 1048576)
	{
		$bytes = number_format($bytes / 1048576, 2) . ' MB';
	}
	elseif ($bytes >= 1024)
	{
		$bytes = number_format($bytes / 1024, 2) . ' KB';
	}
	elseif ($bytes > 1)
	{
		$bytes = $bytes . ' bytes';
	}
	elseif ($bytes == 1)
	{
		$bytes = $bytes . ' byte';
	}
	else
	{
		$bytes = '0 bytes';
	}

	return $bytes;
}
loading...

Leave a Reply

Your email address will not be published. Required fields are marked *