首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >统计PHP目录中有多少个文件

统计PHP目录中有多少个文件
EN

Stack Overflow用户
提问于 2012-10-09 21:38:13
回答 13查看 187.1K关注 0票数 125

我正在做一个稍微新的项目。我想知道某个目录中有多少个文件。

代码语言:javascript
复制
<div id="header">
<?php 
    $dir = opendir('uploads/'); # This is the directory it will count from
    $i = 0; # Integer starts at 0 before counting

    # While false is not equal to the filedirectory
    while (false !== ($file = readdir($dir))) { 
        if (!in_array($file, array('.', '..') and !is_dir($file)) $i++;
    }

    echo "There were $i files"; # Prints out how many were in the directory
?>
</div>

这就是我到目前为止(通过搜索)得到的信息。但是,它没有正确地出现吗?我已经添加了一些注释,所以请随意删除它们,它们只是为了让我能尽可能地理解它。

如果您需要更多信息,或者觉得我对此描述得还不够充分,请随时说明。

EN

回答 13

Stack Overflow用户

回答已采纳

发布于 2012-10-09 22:01:22

您可以简单地执行以下操作:

代码语言:javascript
复制
$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));
票数 290
EN

Stack Overflow用户

发布于 2012-10-09 21:44:03

您可以像这样获取文件计数:

代码语言:javascript
复制
$directory = "/path/to/dir/";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
 $filecount = count($files);
}
echo "There were $filecount files";

"*"所在的位置,您可以像"*.jpg"一样将其更改为特定的文件类型,也可以执行多种文件类型,如下所示:

代码语言:javascript
复制
glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)

GLOB_BRACE标志扩展{a,b,c}以匹配'a‘、'b’或'c‘

票数 79
EN

Stack Overflow用户

发布于 2012-10-09 21:41:42

尝尝这个。

代码语言:javascript
复制
// Directory
$directory = "/dir";

// Returns an array of files
$files = scandir($directory);

// Count the number of files and store them inside the variable..
// Removing 2 because we do not count '.' and '..'.
$num_files = count($files)-2);
票数 45
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12801370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档