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

April 30th, 2012 by Laeeq | No comments

Sometimes we need to get file sizes in different format like KB, MB and GB. Here’s very simple PHP function that will display file size in KB, MB or GB. You can easilly get your desired result just passing your desired format in function’s type parameter.

function formatFilebytes($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;}
}

Example:

echo formatFilebytes(“$_SERVER[DOCUMENT_ROOT]/images/large_picture.jpg”, “MB”);
// would display the file size in MB

Hope it will work for you!

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Read and write to remote files using PHP
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  •  

     

    1. No comments yet.
    1. No trackbacks yet.