<?php
$path = '/var/www/html';
function filesize_recursive($path)
{
$ret = 0;
try
{
if(!file_exists($path)) return 0;
if(is_file($path)) return filesize($path);
foreach(glob($path."/*") as $fn)
$ret += filesize_recursive($fn);
}
catch(Exception $e)
{
echo 'Message: ' .$e->getMessage();
}
return $ret;
}
function display_size($size)
{
$sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$retstring = '%01.2f %s';
$lastsizestring = end($sizes);
foreach ($sizes as $sizestring)
{
if ($size < 1024) { break;}
if ($sizestring != $lastsizestring) { $size /= 1024; }
}
if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; }
return sprintf($retstring, $size, $sizestring);
}
echo "Folder {$path} size: ".display_size(filesize_recursive($path))."";
?>
<?PHP
function ByteSize($bytes)
{
$size = $bytes / 1024;
if($size < 1024)
{
$size = number_format($size, 2);
$size .= ' KB';
}
else
{
if($size / 1024 < 1024)
{
$size = number_format($size / 1024, 2);
$size .= ' MB';
}
else if ($size / 1024 / 1024 < 1024)
{
$size = number_format($size / 1024 / 1024, 2);
$size .= ' GB';
}
}
return $size;
}
function recursive_directory_size($directory, $format=FALSE)
{
$size = 0;
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory) || !is_readable($directory))
{
return -1;
}
if($handle = opendir($directory))
{
while(($file = readdir($handle)) !== false)
{
$path = $directory.'/'.$file;
if($file != '.' && $file != '..')
{
if(is_file($path))
{
$size += filesize($path);
}elseif(is_dir($path))
{
$handlesize = recursive_directory_size($path);
if($handlesize >= 0)
{
$size += $handlesize;
}else{
return -1;
}
}
}
}
closedir($handle);
}
if($format == TRUE)
{
if($size / 1048576 > 1)
{
return round($size / 1048576, 1).' MB';
}elseif($size / 1024 > 1)
{
return round($size / 1024, 1).' KB';
}else{
return round($size, 1).' bytes';
}
}else{
return $size;
}
}
// Show disk space used by your complete site
echo '<p>'. $_SERVER['DOCUMENT_ROOT'].'/<br>';
$f = $_SERVER['DOCUMENT_ROOT'].'/';
$size = ByteSize(recursive_directory_size($f));
echo $size;
// Show disk spaced used only in downloads and subdirectories
echo '<p>'. $_SERVER['DOCUMENT_ROOT'].'/downloads/<br>';
$f = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
$size = ByteSize(recursive_directory_size($f));
echo $size;
?>
Originally Posted on February 23, 2016
Last Updated on January 4, 2017
Last Updated on January 4, 2017
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.