Friday, 3 June 2016

PHP- COUNT FILES IN A DIRECTORY

I’ve just added a new feature to the Team page, where i’ve added a small CSS image gallery. So now you can see multiple images of the awesome BrightCherryteam!
I like everything to be automated so there is very little input from a human to make things work. To help make the thumbnail image gallery completely automated and dynamic, I needed to get a count of how many images there are in each member’s image folder.
Count files
So for example, if Harry our Sales Director has 2 images of himself in his images folder, our script will automatically pull out 2 images. If he uploads a new image of himself in his folder, our script will automatically pull out 3 images. In order for that to work, I needed to write a line of PHP code that counts how many image files there are in his image folder each time the page loads.
I’ve seen plenty of PHP code out there that does a file count in a directory. To be honest, most of the code i’ve seen has been bloated- code that is far too long. All you really need is 1 line of code to do a file count.
Here’s the code I used to count how many files there are in a directory:
1
2
3
4
5
6
7
8
9
10
$directory = "../images/team/harry/";
if (glob($directory . "*.jpg") != false)
{
 $filecount = count(glob($directory . "*.jpg"));
 echo $filecount;
}
else
{
 echo 0;
}
In my particular example, it’s only counting files with a jpg extension. You can change that to anything (i.e txt), or completely remove it if you want to count all files. The * is acting as a wildcard.

0 comments:

Post a Comment