Fastest Way To Format File Size In PHP

Overview

In this short post, you will find a PHP function that has got to be the quickest way to convert bytes into an easier to read format of kilobytes, megabytes, gigabytes and petabytes. The PHP filesize convert function below takes the number (as bytes) passed to it and will convert it into an easier to read format. It will also round off the result to 2 decimal places. Very convenient and free from my site.

Fastest Way To Format File Size In PHP

The PHP convert function will take the number passed to it and continually loop and divide the number by 1024. We divide by 1024 since that is the number of bytes in a kilobyte as well as the number of kilobytes in a megabyte and so on. Each time we divide by 1024, we see if the result is still bigger than 1024. Once the number is less than 1024, we then count the number of times we had to divide the original number and that will tell us if the number is B, KB, MB, etc. For example, if we divided the number 3 times, that would mean the original number is in the GB. So we get the third element out of our $types array which returns GB.

<?php

function formatSize( $bytes )
{
	$types = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
	for( $i = 0; $bytes >= 1024 && $i < ( count( $types ) -1 ); $bytes /= 1024, $i++ );
		return( round( $bytes, 2 ) . " " . $types[$i] );
}

Usage Examples

Below are some examples on how to format file size in php using the above function.

<?php

// call the above formatSize function and pass it a number as bytes

echo formatSize(8763432); // will echo 8.35 MB
echo formatSize(258); // will echo 258 B
echo formatSize( filesize('/path/to/some/file'); // will echo out the file size of that file

 ?>