如何解决php计算一个目录文件夹的权重
我想在 PHP 中计算一个目录的权重,然后按照下面的例子显示数据。
Example:
Storage
50 GB (14.12%) of 353 GB used
<?PHP
$dir = ('D:\data');
echo "Size : " Fsize($dir);
function Fsize($dir)
{
if (is_dir($dir))
{
if ($gd = opendir($dir))
{
$cont = 0;
while (($file = readdir($gd)) !== false)
{
if ($file != "." && $file != ".." )
{
if (is_dir($file))
{
$cont += Fsize($dir."/".$file);
}
else
{
$cont += filesize($dir."/".$file);
echo "file : " . $dir."/".$file . " " . filesize($dir."/".$file)."<br />";
}
}
}
closedir($gd);
}
}
return $cont;
}
?>
它显示的文件夹大小为3891923
,但不是实际大小,验证目录时实际大小为191791104 bytes
你能帮我吗?
解决方法
您对目录的测试在这里不正确:
if (is_dir($file)) // This test is missing the directory component
{
$cont += Fsize($dir."/".$file);
}
else
试试:
if (is_dir("$dir/$file")) // This test adds the directory path
{
$cont += Fsize($dir."/".$file);
}
else
PHP 提供了许多 iterators 可以简化如下操作:
$path = "path/to/folder";
$Directory = new RecursiveDirectoryIterator($path);
$Iterator = new RecursiveIteratorIterator($Directory);
$Iterator->setFlags(FilesystemIterator::SKIP_DOTS);
$totalFilesize = 0;
foreach($Iterator as $file){
if ($file->isFile()) {
$totalFilesize += $file->getSize();
}
}
echo "Total: $totalFilesize";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。