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)
      case \"KB\":
         $filesize = filesize($file) * .0009765625; // bytes to KB
      case \"MB\":
         $filesize = (filesize($file) * .0009765625) * .0009765625; // bytes to MB
      case \"GB\":
         $filesize = ((filesize($file) * .0009765625) * .0009765625) * .0009765625; // bytes to GB
   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