使用PHP脚本获取远程主机上的目录大小

时间:2020-03-05 18:43:44  来源:igfitidea点击:

我正在寻找可以递归显示主文件夹中每个文件夹大小的东西。

这是一个带有CGI-Bin的LAMP服务器,因此大多数任何PHP脚本都应该可以工作,或者在CGI-Bin中可以工作的任何东西。

我的托管公司没有为我提供界面,以查看哪些文件夹占用最多的空间。我对互联网一无所知,进行了几次搜索,但没有结果。

最好使用某种实现图(GD / ImageMagick),但不是必需的。

我的主机仅在CGI-BIN中支持Perl。

解决方案

回答

奇怪,我在Google上提出了许多相关的结果,而这个结果可能是最完整的。

The function "getDirectorySize" will
  ignore link/shorcuts to
  files/directory. The function
  "sizeFormat" will suffix the size with
  bytes,KB,MB or GB accordingly.

代码

function getDirectorySize($path)
{
  $totalsize = 0;
  $totalcount = 0;
  $dircount = 0;
  if ($handle = opendir ($path))
  {
    while (false !== ($file = readdir($handle)))
    {
      $nextpath = $path . '/' . $file;
      if ($file != '.' && $file != '..' && !is_link ($nextpath))
      {
        if (is_dir ($nextpath))
        {
          $dircount++;
          $result = getDirectorySize($nextpath);
          $totalsize += $result['size'];
          $totalcount += $result['count'];
          $dircount += $result['dircount'];
        }
        elseif (is_file ($nextpath))
        {
          $totalsize += filesize ($nextpath);
          $totalcount++;
        }
      }
    }
  }
  closedir ($handle);
  $total['size'] = $totalsize;
  $total['count'] = $totalcount;
  $total['dircount'] = $dircount;
  return $total;
}

function sizeFormat($size)
{
    if($size<1024)
    {
        return $size." bytes";
    }
    else if($size<(1024*1024))
    {
        $size=round($size/1024,1);
        return $size." KB";
    }
    else if($size<(1024*1024*1024))
    {
        $size=round($size/(1024*1024),1);
        return $size." MB";
    }
    else
    {
        $size=round($size/(1024*1024*1024),1);
        return $size." GB";
    }

}

用法

$path="/httpd/html/pradeep/";
$ar=getDirectorySize($path);

echo "<h4>Details for the path : $path</h4>";
echo "Total size : ".sizeFormat($ar['size'])."<br>";
echo "No. of files : ".$ar['count']."<br>";
echo "No. of directories : ".$ar['dircount']."<br>";

输出

Details for the path : /httpd/html/pradeep/
Total size : 2.9 MB
No. of files : 196
No. of directories : 20

回答

如果我们具有外壳程序访问权限,则可以运行以下命令

$ du -h

如果PHP配置为允许执行,则可以使用以下方法:

<?php $d = escapeshellcmd(dirname(__FILE__)); echo nl2br(`du -h $d`) ?>