Here’s the follow-up article on how to easily get file sizes nicely formated. Below is a quick function that will display the file size in KB, MB, or GB all easily accessed through a function.
function formatbytes($file, $type)
{
switch($type){
case "KB":
$filesize = filesize($file) * .0009765625; // bytes to KB
break;
case "MB":
$filesize = (filesize($file) * .0009765625) * .0009765625; // bytes to MB
break;
case "GB":
$filesize = ((filesize($file) * .0009765625) * .0009765625) * .0009765625; // bytes to GB
break;
}
if($filesize <= 0){
return $filesize = 'unknown file size';}
else{return round($filesize, 2).' '.$type;}
}
// USAGE
echo formatbytes("$_SERVER[DOCUMENT_ROOT]/images/large_picture.jpg", "MB");
// would display the file size in MB
Just remember the file location has to be the absolute location on the server. It can not be relative ('/images/....') Please let me know if you have any questions about any of this.
Similar Posts:
- Fade In and Out Images from a Single Directory Using jQuery (with plugin)
- PHP File Last Modified and Filesize (bytes to KB/MB)
- Find Time Between Two Dates in PHP
- UPDATED: Strip Off Characters from String Using PHP (substr)
- Display Last.fm’s Recent Tracks on Web Site with PHP Function
Tags: php

September 18th, 2008 @ 8:22 am
many thanks.
its powerfull.
September 28th, 2008 @ 6:48 am
excelent thank you !
November 18th, 2008 @ 1:37 pm
I’ve tried using the above function, but when the code gets to the bit that displays the filesize it stops running and nothing below that point runs. I suspect it could be to do with the path to my image, but I’ve tried lots of variations without success. Also, I don’t understand the $_SERVER[DOCUMENT_ROOT] – I’ve tried with and without this. Any suggestions?
November 18th, 2008 @ 1:42 pm
I think I’ve narrowed it down to something in the main function block of code, but I don’t know what? Is there anything in there that is only compatible with PHP5 as my server is PHP4 at the moment?
December 9th, 2008 @ 11:36 pm
This should work with PHP4 & 5
December 30th, 2008 @ 7:43 pm
Hi,
Thanks for the script.
May i ask you something?
How can we modify that,so that in case that the file is under 1mb to be shown as number in KB and if it is more than 1mb then to be shown in MB?
Thanks.
December 31st, 2008 @ 2:22 pm
That’s a good idea. I’ll post an updated version shortly that will have that feature.
February 28th, 2009 @ 1:56 pm
Wonderful! Exactly what i needed today
April 23rd, 2009 @ 5:56 am
Thanx for the script!
August 4th, 2009 @ 1:56 pm
This is more versatile, in my opinion: http://aidanlister.com/2004/04/human-readable-file-sizes/
No need to specify a type, it does it automatically and gives other options…