Quick 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/....\')


comments powered by Disqus