To convert bytes to human readable file size in PHP you can use the following snippet.

Sample PHP

function BytesToHumanReadableSize($bytes)
{
	$unit = null;
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
	
	for($Counter = 0, $c = count($units); $Counter < $c; $Counter++)
	{
		if ($bytes > 1024)
		{
			$bytes = $bytes / 1024;
		}
		else
		{
			$unit = $units[$Counter];
			break;
		}
	}
 
	return round($bytes, 2). ' ' .$unit;
}

One thought on “How to convert bytes to human readable file size in PHP”

Leave a Reply