Return total number of files within a folder using PHP

36,496

Solution 1

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

Solution 2

This will give you the count of what is in your dir. I'll leave the part about counting only images to you as I am about to fallll aaasssllleeelppppppzzzzzzzzzzzzz.

iterator_count(new DirectoryIterator('path/to/dir/'));

Solution 3

i do it like this:

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

but it also counts the . and ..

Solution 4

The aforementioned code

$count = count(glob("*.{jpg,png,gif,bmp}"));

is your best best, but the {jpg,png,gif} bit will only work if you append the GLOB_BRACE flag on the end:

$count = count(glob("*.{jpg,png,gif,bmp}", GLOB_BRACE));

Solution 5

you could use glob...

$count = 0;
foreach (glob("*.*") as $file) {
    if (isImage($file)) ++$count;
}

or, I'm not sure how well this would suit your needs, but you could do this:

$count = count(glob("*.{jpg,png,gif,bmp}"));
Share:
36,496
warnabas
Author by

warnabas

Passionate PHP developer Penguin Linux junkie Desktop computer Avid PC gamer Coffee aficionado Woman and man holding hands Dedicated husband Family (man, girl, boy) Proud father of two

Updated on December 21, 2020

Comments

  • warnabas
    warnabas over 3 years

    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 = readdir($dir)) !== false) {
        if (isImage($file)) {$x = $x + 1}
      }
      return $x;
    }
    

    This seems like such a long way of doing this, is there no simpler way?

    Note: The isImage() function returns true if the file is an image.

  • rg88
    rg88 over 15 years
    That's what I was about to post. I think your solution is the way to go.
  • warnabas
    warnabas over 15 years
    AWSOME! Just what I was looking for!
  • GnomeCubed
    GnomeCubed over 15 years
    If you find that your isImage() function and current method is slow I think that doing a ls and piping it to wc -l might be faster. I would only do that IF your current method is slow though, because your right about the security reasons for not using system/exec.
  • Brian
    Brian over 11 years
    It also retrieves folders, so as far as I know you should loop through the $files array and check if it's a file using is_file.