Return total number of files within a folder using PHP

前端 未结 10 881
花落未央
花落未央 2020-12-28 20:31

Is there a better/simpler way to find the number of images in a directory and output them to a variable?

function dirCount($dir) {
  $x = 0;
  while (($file          


        
相关标签:
10条回答
  • 2020-12-28 21:08

    Check out the Standard PHP Library (aka SPL) for DirectoryIterator:

    $dir = new DirectoryIterator('/path/to/dir');
    foreach($dir as $file ){
      $x += (isImage($file)) ? 1 : 0;
    }
    

    (FYI there is an undocumented function called iterator_count() but probably best not to rely on it for now I would imagine. And you'd need to filter out unseen stuff like . and .. anyway.)

    0 讨论(0)
  • 2020-12-28 21:09

    Your answer seems about as simple as you can get it. I can't think of a shorter way to it in either PHP or Perl.

    You might be able to a system / exec command involving ls, wc, and grep if you are using Linux depending how complex isImage() is.

    Regardless, I think what you have is quite sufficient. You only have to write the function once.

    0 讨论(0)
  • 2020-12-28 21:11

    I use the following to get the count for all types of files in one directory in Laravel

       $dir = public_path('img/');
        $files = glob($dir . '*.*');
    
        if ( $files !== false )
        {
            $total_count = count( $files );
            return $totalCount;
        }
        else
        {
            return 0;
        }
    
    0 讨论(0)
  • 2020-12-28 21:13

    i do it like this:

    $files = scandir($dir);
    $x = count($files);
    echo $x;
    

    but it also counts the . and ..

    0 讨论(0)
提交回复
热议问题