【问题标题】:How to count all folder ,file and files in sub folder in server using php?如何使用php计算服务器中子文件夹中的所有文件夹、文件和文件?
【发布时间】:2015-12-06 13:54:34
【问题描述】:

如何使用php统计服务器中所有文件夹、文件和子文件夹中的文件?

我想计算路径/home1/example/public_html/中子文件夹中的所有文件、文件夹和文件

首先我使用这个代码

<?php 
$directory = "/home1/example/public_html/";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
 $filecount = count($files);
}
echo "There were $filecount files";
?>

节目There were 561 files

然后我使用这个代码

<?php 
$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));
?>

节目There were 566 Files

最后我使用了这段代码

<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = '/home1/example/public_html/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
                $i++;
        }
    }
    // prints out how many were in the directory
    echo "There were $i files";
?>`

节目There were 500 Files

但结果不同。

我通过在/home1/example/public_html/images/ 中创建文件进行了测试,但所有结果仍然显示与我创建文件之前相同。

我该怎么办?

【问题讨论】:

    标签: php file directory


    【解决方案1】:

    您的第二个示例将返回比第一个更精确的答案,因为glob 忽略隐藏文件而FilesystemIterator 不会。

    第三个示例的最大区别在于,在 #1 和 #2 中,您正在迭代然后计算文件和目录,而在 #3 中,您正在过滤计数中的目录(通过调用 is_dir)。

    所以#3 可能是正确的(除了我在下面的注释中提到的),我建议使用#2 的变体,这样会更容易阅读:

    function recursive_file_count($dir)
    {
        $fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
        $c = 0;
        foreach ($fi as $fileInfo)
        {
            if (!$fileInfo->isDir()) { ++$c; }
            // can also test for $fileInfo->isLink() if needed
        }
        return $c;
    }
    

    注意:计数也受文件系统权限的影响。因此,例如,如果这个脚本在 Apache 中以 httpd 用户运行,并且 httpd 对某个目录没有执行权限,那么它将无法进入该目录并统计其文件。如果没有某种邪恶的提权黑客,就没有办法解决这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      相关资源
      最近更新 更多