18 June 2015

PHP cookies based unique hit counter (side project)

In this post I'll show you a simple implementation of an unique hit counter that can be used wherever you need to.
This counter is cookies based, so obviously if the visitors of your blog/website disables the cookies in their browser this script will not work as expected, in fact if the cookies are disabled the script can no longer know if the actual user has been already counted or not, for this reason there are other implementations that rely on the user IP, anyway, personally I think that for an hit counter a cookies based solution is good enough.
Now I'll explain how the script works, but first let's take a look at the code:

Hit counter source code opened with Geany
As you can see from the code above the script prints the visits number that has been read from the website database, than it creates a cookie named "visited" and, if the user hasn't already this cookie, gives it to the user and updates the visits number in the database. If the user will visit this page again before the expiration date of the cookie his visit will not be counted because the script will update the visits number only if the user hasn't the cookie named "visited".
You can find the source code for the hit counter in the download section of the blog.

No comments:

Post a Comment