计算目录php中有多少个文件

我正在做一个新项目。我想知道如何制作它,以便计算某个目录中有多少个文件。


<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>

这是我到目前为止(从搜索中获得的)。但是它显示不正确吗?我添加了一些注释,以便随时删除它们,它们是为了使我能尽我所能。


如果您需要更多信息,或者觉得我还没有足够描述,请随时声明。


慕的地10843
浏览 480回答 3
3回答

拉风的咖菲猫

您可以简单地执行以下操作:$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);printf("There were %d Files", iterator_count($fi));

慕森卡

您可以这样获取文件计数:$directory = "/path/to/dir/";$filecount = 0;$files = glob($directory . "*");if ($files){&nbsp;$filecount = count($files);}echo "There were $filecount files";"*"您可以在哪里将其更改为特定的文件类型,"*.jpg"也可以执行以下多种文件类型:glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)该GLOB_BRACE标志展开{a,b,c}以匹配'a','b'或'c'

湖上湖

你应该有 :<div id="header"><?php&nbsp;&nbsp; &nbsp; // integer starts at 0 before counting&nbsp; &nbsp; $i = 0;&nbsp;&nbsp; &nbsp; $dir = 'uploads/';&nbsp; &nbsp; if ($handle = opendir($dir)) {&nbsp; &nbsp; &nbsp; &nbsp; while (($file = readdir($handle)) !== false){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $i++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // prints out how many were in the directory&nbsp; &nbsp; echo "There were $i files";?></div>
打开App,查看更多内容
随时随地看视频慕课网APP