note 114950 deleted from function.filesize by tularis
| From: | tularis@php.net | Date: | Sun, 04 May 2014 09:04:30 +0000 |
| Subject: | note 114950 deleted from function.filesize by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199407@lists.php.net to get a copy of this message | ||
Note Submitter: stlawson at joyfulearthtech dot com
----
Here's a more efficient "Human Readable" file size function:
/**
* Returns file size in a more Human Readable format (i.e. truncates larger file
* sizes and adds appropriate suffix, such as KB for "kilobyte" or MB for
"megabyte" etc.
*
* @param type $filesize in Bytes
* @return string
* @throws RuntimeException
* @author S. T. Lawson
*/
function human_readable_filesize($filesize)
{
if (is_nan($filesize))
{
throw new RuntimeException("filesize argument contains NAN!");
}
// Prevent endless loop
$max_step = 8;
// Strip out any commas.
$filesize = str_replace(',','',$filesize);
if (is_numeric($filesize))
{
$divr = 1024; $step = 0;
$suffix =
array('Byte','KB','MB','GB','TB','PB','EB','ZB','YB');
while($filesize >= 1023.99)
{
if ($step++ > $max_step) { throw new RuntimeException("Max # of loop iterations
[$max_step] exceeded while attempting to convert $filesize!"); }
$filesize = $filesize / $divr;
}
return round($filesize, 2).' '.$suffix[$step];
}
else
{
throw new RuntimeException("filesize argument [$filesize] is non-numeric!");
}
}