This tutorial will show you how you can create a counter in PHP that will keep track and display your number of visitors on a website. I will present two ways of doing this: first one would be to use a MySQL a data to keep the nr. of files, and second one to store the nr. in a file.
First we create our table in counter database:
The code above is meant to make a short review on how to connect to a database and perform a query. This can be achieve also using
phpMyAdmin which is a faster way to do it. Count is of type Int(8) which can store a value up to 99.999.999. Also I reset the counter
to 0 using INSERT query.
I will explain the PHP code: When a visitor enters on the page I’m connecting to the database and I add + 1 to the existing value. After that
I retrieve the number of visitors and display the value in a single cell table. We can put this into a counter.php file for example and include
it using include directive where we want to be displayed.
The second approach in how to make a PHP counter would be to use a file.
In this simple code I am opening visitors.txt the in an array. Then I increment with +1 the value of existing number and write it into the file.
The file that you will use must have 777 rights. After that I simply display the value. You can put this also in a file and include it as with
the MySQL version.
A link to see how PHP counts the nr. of visitors :
Thank you reading this tutorial!
Leave a Reply