PHP File Size Bytes Convert To KB MB GB TB

Convert file size to human readable format in PHP. Converting bytes to human readable values (KB, MB, GB, TB, PB) PHP function

1 Byte = 8 Bits
1 Kilobyte = 1024 Bytes
1 Megabyte = 1048576 Bytes
1 Gigabyte = 1073741824 Bytes
1 Terabyte = 1099511627776 bytes

PHP Function Format Bytes

PHP
<?php
function formatBytes($bytes) {
	if ($bytes > 0) {
		$i = floor(log($bytes) / log(1024));
		$sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
		return sprintf('%.02F', round($bytes / pow(1024, $i),1)) * 1 . ' ' . @$sizes[$i];
	} else {
		return 0;
	}
}
?>

Usage PHP Format Bytes

PHP
<?php
echo formatBytes('1000'); // 1000B

echo formatBytes('1073741824'); //1GB

$file_size = filesize('myfile.zip'); // Get file size
echo '<div title="'.$file_size.' bytes">'.formatBytes($file_size).'</div>';

 //output 
 //<div title="1073741824 bytes">1 GB</div>
?>