Jump to content

Get filsize in kb, mb, gb.. just want to improve code I've got.


Dragen

Recommended Posts

Hi,

I've written this function to check a filesize, then give it the correct filesize abbreviation (kb, mb, gb).

Here's my code:

<?php
$size = filesize('myfile');
					if($size > 1024 && $size < 1048576){
						$size = $size/1024;
						$downsize = 'kb';
					}elseif($size >= 1048576 && $size < 1073741824){
						$size = $size/1048576;
						$downsize = 'mb';
					}elseif($size >= 1073741824){
						$size = $size/1073741824;
						$downsize = 'gb';
					}
					echo round($size, 1) . $downsize;
?>

This works absolutely fine. I was just wondering if anyone knew of a way I could shorten my code a bit?

 

Thanks

Looks fine to me, but on the elseif's you do not need to check the lower end because if the file was smaller it would have been processed by one of the previous tests. Also, you need to make the size descriptions UPPERCASE. mb = megabits MB = megabytes

 

 

however, I am always looking to make my code as efficient as possible as well and found another script online and decided to spruce it up. I like this approach as it is mostly automated and you just need to add additional descriptors to the array and do not need to worry about determining the bytes needed for each descriptor:

 

<?php

function fileSizeInfo ($size) {

  $sizeArray = array ('KB', 'MB', 'GB', 'TB');

  do {
    $size = $size/1024;
    $downsize=(isset($downsize))?$downsize+1:0;

  } while ($size>=1024 && $downsize<count($sizeArray)-1);

  return array('size'=>$size , 'downsize'=>$sizeArray[$downsize]);

}

$size = filesize('myfile');
$fileInfo = fileSizeInfo ($size);

echo round($fileInfo['size'], 1) . " " . $fileInfo['downsize'];

?>

Ok, made some more modifications and added some error handling. Function now allows you to determine the precision of the returned value (default is 2). Going to save this one away for future use.

 

<?php

function fileSizeInfo ($size, $precision=2) {

  if (!is_numeric($size) || !is_numeric($precision)) { return false; }

  $unitArray = array ('B', 'KB', 'MB', 'GB', 'TB');
  $unit = 0;

  while ($size>=1024 && $unit<count($unitArray)-1) {
    $size = $size/1024;
    $unit++;
  }

  $size = round($size, $precision);
  return array ('size'=>round($size, $precision), 'unit'=>$unitArray[$unit]);

}


//$size = filesize('myfile');
$fileData =  fileSizeInfo ($size, 1);
echo "<br>". $fileData['size'] . " " . $fileData['unit'];

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.