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

发布于 2024-07-04 14:31:28 字数 537 浏览 7 评论 0原文

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

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

我的托管公司没有提供界面让我查看哪些文件夹占用的空间最多。 我对互联网上的任何内容一无所知,并进行了一些搜索,但没有得到任何结果。

实现图形的东西(GD/ImageMagick) 是最好的,但不是必需的。

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

I'm looking for something that will show me the size of each folder within my main folder recursively.

This is a LAMP server with a CGI-Bin so most any PHP script should work or anything that will work in the CGI-Bin.

My hosting company does not provide an interface for me to see which folders are consuming the most amount of space. I don't know of anything on the Internet and did a few searches however I came up with no results.

Something implementing graphs (GD/ImageMagick) would be best but not required.

My host supports only Perl in the CGI-BIN.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

書生途 2024-07-11 14:31:28

number_files_and_size.php

<?php
if (isset($_POST["nivel"])) {
        $mostrar_hasta_nivel = $_POST["nivel"];
        $comenzar_nivel_inferior = $_POST["comenzar_nivel_inferior"];
        // $mostrar_hasta_nivel = 3;

        global $nivel_directorio_raiz;
        global $nivel_directorio;

        $path = dirname(__FILE__);
        if ($comenzar_nivel_inferior == "si") {
            $path = substr($path, 0, strrpos($path, "/"));
        }
        $nivel_directorio_raiz = count(explode("/", $path)) - 1;
        $numero_fila = 1;


        // Comienzo de Tabla
        echo "<table border='1' cellpadding='3' cellspacing='0'>";
        // Fila encabezado
        echo "<tr style='font-size: 100%; font-weight: bold;' bgcolor='#e2e2e2'><td></td><td>Ruta</td><td align='center'>Nivel</td><td align='right' style='color:#0000ff;'>Ficheros</td><td align='right'>Acumulado fich.</td><td align='right'>Directorio</td><td align='right' style='color:#0000ff;'>Tamaño</td><td align='right'>Acumulado tamaño</td></tr>";
        // Inicio Filas de datos
        echo "<tr>";

        //Función que se invoca a si misma de forma recursiva según recorre el directorio raiz ($path)
        FileCount($path, $mostrar_hasta_nivel, $nivel_directorio_raiz); 

        // Din Filas de datos
        echo "</tr>";
        // Fin de tabla
        echo "</table>";
        echo "<div style='font-size: 120%;'>";
        echo "<br>Total ficheros en la ruta <b><em>" . $path . ":</em> " . number_format($count,0,",",".") . "</b><br>";
        echo "Tamaño total ficheros: <b>". number_format($acumulado_tamanho, 0,",",".") . " Kb.</b><br>";
        echo "</div>";

        echo "<div style='min-height: 60px;'></div>";

} else {
    ?>
    <form name="formulario" id="formulario" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <br /><h2>Informe del Alojamiento por directorios (Número de Archivos y Tamaño)</h2>
        <br />Nivel de directorios a mostrar: <input type="text" name="nivel" id="nivel" value="3"><br /><br />
        <input type="checkbox" name="comenzar_nivel_inferior" value="si" checked="checked"/> Comenzar en nivel de directorio inmediatamente inferior a la ubicación de este módulo PHP<br />(<?php echo dirname(__FILE__) ?>)<br /><br />
        <input type="submit" name="comenzar" id="comenzar" value="Comenzar proceso"><br /><br />
    </form>
    <?php
}




function FileCount($dir, $mostrar_hasta_nivel, $nivel_directorio_raiz){
    global $count;
    global $count_anterior;
    global $suma_tamanho;
    global $acumulado_tamanho;

    $arr=explode('&',$dir);
    foreach($arr as $val){
        global $ruta_actual;

        if(is_dir($val) && file_exists($val)){
            global $total_directorio;
            global $numero_fila;
            $total_directorio = 0;

            $ob=scandir($val);
            foreach($ob as $file){
                if($file=="."||$file==".."){
                    continue;
                }
                $file=$val."/".$file;

                if(is_file($file)){
                    $count++;
                    $suma_tamanho = $suma_tamanho + filesize($file)/1024;
                    $acumulado_tamanho = $acumulado_tamanho + filesize($file)/1024;
                    $total_directorio++;
                } elseif(is_dir($file)){
                    FileCount($file, $mostrar_hasta_nivel, $nivel_directorio_raiz);
                }
            }

            $nivel_directorio = count(explode("/", $val)) - 1;

            if ($nivel_directorio > $mostrar_hasta_nivel) {
            } else {
                $atributo_fila = (($numero_fila%2)==1 ? "background-color:#ffffff;" : "background-color:#f2f2f2;");
                echo "<tr style='".$atributo_fila."'><td>".$numero_fila."</td><td>".$val."    </td><td align='center'>".$nivel_directorio."</td><td align='right' style='color:#0000ff;'>".number_format(($count - $count_anterior),0,",",".")."</td><td align='right'>".number_format($count,0,",",".")."</td><td align='right'>".number_format($total_directorio,0,",",".")."</td><td align='right' style='color:#0000ff;'>".number_format($suma_tamanho,0,",",".")." Kb.</td><td align='right'>".number_format($acumulado_tamanho,0,",",".")." Kb.</td></tr>";

                $count_anterior = $count;
                $suma_tamanho = 0;
                $numero_fila++;
            }

        }
    }
}
?>

number_files_and_size.php

<?php
if (isset($_POST["nivel"])) {
        $mostrar_hasta_nivel = $_POST["nivel"];
        $comenzar_nivel_inferior = $_POST["comenzar_nivel_inferior"];
        // $mostrar_hasta_nivel = 3;

        global $nivel_directorio_raiz;
        global $nivel_directorio;

        $path = dirname(__FILE__);
        if ($comenzar_nivel_inferior == "si") {
            $path = substr($path, 0, strrpos($path, "/"));
        }
        $nivel_directorio_raiz = count(explode("/", $path)) - 1;
        $numero_fila = 1;


        // Comienzo de Tabla
        echo "<table border='1' cellpadding='3' cellspacing='0'>";
        // Fila encabezado
        echo "<tr style='font-size: 100%; font-weight: bold;' bgcolor='#e2e2e2'><td></td><td>Ruta</td><td align='center'>Nivel</td><td align='right' style='color:#0000ff;'>Ficheros</td><td align='right'>Acumulado fich.</td><td align='right'>Directorio</td><td align='right' style='color:#0000ff;'>Tamaño</td><td align='right'>Acumulado tamaño</td></tr>";
        // Inicio Filas de datos
        echo "<tr>";

        //Función que se invoca a si misma de forma recursiva según recorre el directorio raiz ($path)
        FileCount($path, $mostrar_hasta_nivel, $nivel_directorio_raiz); 

        // Din Filas de datos
        echo "</tr>";
        // Fin de tabla
        echo "</table>";
        echo "<div style='font-size: 120%;'>";
        echo "<br>Total ficheros en la ruta <b><em>" . $path . ":</em> " . number_format($count,0,",",".") . "</b><br>";
        echo "Tamaño total ficheros: <b>". number_format($acumulado_tamanho, 0,",",".") . " Kb.</b><br>";
        echo "</div>";

        echo "<div style='min-height: 60px;'></div>";

} else {
    ?>
    <form name="formulario" id="formulario" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <br /><h2>Informe del Alojamiento por directorios (Número de Archivos y Tamaño)</h2>
        <br />Nivel de directorios a mostrar: <input type="text" name="nivel" id="nivel" value="3"><br /><br />
        <input type="checkbox" name="comenzar_nivel_inferior" value="si" checked="checked"/> Comenzar en nivel de directorio inmediatamente inferior a la ubicación de este módulo PHP<br />(<?php echo dirname(__FILE__) ?>)<br /><br />
        <input type="submit" name="comenzar" id="comenzar" value="Comenzar proceso"><br /><br />
    </form>
    <?php
}




function FileCount($dir, $mostrar_hasta_nivel, $nivel_directorio_raiz){
    global $count;
    global $count_anterior;
    global $suma_tamanho;
    global $acumulado_tamanho;

    $arr=explode('&',$dir);
    foreach($arr as $val){
        global $ruta_actual;

        if(is_dir($val) && file_exists($val)){
            global $total_directorio;
            global $numero_fila;
            $total_directorio = 0;

            $ob=scandir($val);
            foreach($ob as $file){
                if($file=="."||$file==".."){
                    continue;
                }
                $file=$val."/".$file;

                if(is_file($file)){
                    $count++;
                    $suma_tamanho = $suma_tamanho + filesize($file)/1024;
                    $acumulado_tamanho = $acumulado_tamanho + filesize($file)/1024;
                    $total_directorio++;
                } elseif(is_dir($file)){
                    FileCount($file, $mostrar_hasta_nivel, $nivel_directorio_raiz);
                }
            }

            $nivel_directorio = count(explode("/", $val)) - 1;

            if ($nivel_directorio > $mostrar_hasta_nivel) {
            } else {
                $atributo_fila = (($numero_fila%2)==1 ? "background-color:#ffffff;" : "background-color:#f2f2f2;");
                echo "<tr style='".$atributo_fila."'><td>".$numero_fila."</td><td>".$val."    </td><td align='center'>".$nivel_directorio."</td><td align='right' style='color:#0000ff;'>".number_format(($count - $count_anterior),0,",",".")."</td><td align='right'>".number_format($count,0,",",".")."</td><td align='right'>".number_format($total_directorio,0,",",".")."</td><td align='right' style='color:#0000ff;'>".number_format($suma_tamanho,0,",",".")." Kb.</td><td align='right'>".number_format($acumulado_tamanho,0,",",".")." Kb.</td></tr>";

                $count_anterior = $count;
                $suma_tamanho = 0;
                $numero_fila++;
            }

        }
    }
}
?>
迷荒 2024-07-11 14:31:28

如果您有 shell 访问权限,则可以运行该命令

$ du -h

,或者如果 PHP 配置为允许执行,则可以使用该命令:

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

If you have shell access you can run the command

$ du -h

or perhaps use this, if PHP is configured to allow execution:

<?php $d = escapeshellcmd(dirname(__FILE__)); echo nl2br(`du -h $d`) ?>
紫竹語嫣☆ 2024-07-11 14:31:28

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

函数“getDirectorySize”将
忽略链接/快捷方式
文件/目录。 功能
“sizeFormat”将在尺寸后添加后缀
相应的字节、KB、MB 或 GB。

代码

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

Strange, I came up on Google with many relevant results and this one is probably the most complete.

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

Code

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";
    }

}

Usage

$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>"; 

Output

Details for the path : /httpd/html/pradeep/
Total size : 2.9 MB
No. of files : 196
No. of directories : 20
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文