PHP Function to Get File Sizes in KB, MB & GB

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 - would display the file size in MB
echo formatbytes("$_SERVER[DOCUMENT_ROOT]/images/large_picture.jpg", "MB");

Just remember the file location has to be the absolute location on the server. It can not be relative ('/images/....')

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s