Return total number of files within a folder using PHP
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}"));
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, 2020Comments
-
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 over 15 yearsThat's what I was about to post. I think your solution is the way to go.
-
warnabas over 15 yearsAWSOME! Just what I was looking for!
-
GnomeCubed over 15 yearsIf 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 over 11 yearsIt also retrieves folders, so as far as I know you should loop through the
$files
array and check if it's a file usingis_file
.