Skip to content

Instantly share code, notes, and snippets.

@thiagoeliasr
Last active November 23, 2016 13:22
Show Gist options
  • Save thiagoeliasr/8d6973c0d0198e9b916e7f85a56a70e6 to your computer and use it in GitHub Desktop.
Save thiagoeliasr/8d6973c0d0198e9b916e7f85a56a70e6 to your computer and use it in GitHub Desktop.
Getting the size of a pre-defined folder and printing on screen the percentage and space available based on a value.
<?php
class Helpers
{
public static function dirSize($dir) {
if(is_file($dir)) return array('size'=>filesize($dir),'howmany'=>0);
if($dh = opendir($dir)) {
$size=0;
$n = 0;
while(($file=readdir($dh))!==false) {
if($file=='.' || $file=='..') continue;
$n++;
$data = self::dirSize($dir.'/'.$file);
$size += $data['size'];
$n += $data['howmany'];
}
closedir($dh);
return ['size' => $size, 'howmany' => $n];
}
return ['size' => 0, 'howmany' => 0];
}
public static function formatSize($fsizebyte) {
if ($fsizebyte < 1024) {
$fsize = $fsizebyte." bytes";
}elseif (($fsizebyte >= 1024) && ($fsizebyte < 1048576)) {
$fsize = round(($fsizebyte/1024), 2);
$fsize = $fsize." KB";
}elseif (($fsizebyte >= 1048576) && ($fsizebyte < 1073741824)) {
$fsize = round(($fsizebyte/1048576), 2);
$fsize = $fsize." MB";
}elseif ($fsizebyte >= 1073741824) {
$fsize = round(($fsizebyte/1073741824), 2);
$fsize = $fsize." GB";
};
return $fsize;
}
public static function getUsage($formatado = false, $console = false)
{
$path = "C:\caminho";
$max = 21474836480; //20gb em bytes
$dirSize = self::dirSize($path);
$percentual = number_format(($dirSize['size'] * 100) / (double)$max, 2);
if (!$formatado) {
return $percentual;
} else {
return [
'usado' => self::formatSize($dirSize['size']),
'percentual' => $percentual,
'disponivel' => self::formatSize($max)
];
}
}
}
$armazenamento = Helpers::getUsage(true);
?>
<div class="col-md-3 pull-right">
<div class="col-md-12 well">
<h5 class="title-armazenamento">Armazenamento utilizado: <span class="label <?php echo $labelUtilizado; ?>"><?php echo $armazenamento['usado'];?>
(<?php echo $armazenamento['percentual'];?>%)</span> de
<span class="label label-default"><?php echo $armazenamento['disponivel'];?></label> disponíveis</h5>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment