Unique Visit counter by Storing IP Address using PHP

Hey Technoz, In this tutorial we are going to learn how to get unique visit counter value by using PHP. In previous tutorial we covered how to calculate hit counter for the website. In this tutorial we are focusing on unique visit counter. To do this task efficiently, we are going to store our user IP address in our database and next time when the same user access our website program can easily recognize unique user.

Creating database

A database need to be create to store the information about unique visit counter and user’s IP address

So lets create the database by using following queries. The following SQL  creates two tables namely, counter and ipdb which consist of  id, visitors and ip address of visitors.

Now, Set ‘id’ as primary key and AUTO_INCREMENT ‘id’ of table ipdb by using following queries.

As we did it in the previous tutorial It is important to set all values of the fields equal to zero. For starting counter value from zero.

Now, Lets do this task by using following query.

First, To make it convenient, We will create a new PHP file for database configuration named  dbconfig.php  that holds all configured parameters:

Code of Unique Visit counter by Storing IP Address

The following code  index.php  is consists the script to fetch the user’s ip address and of to Calculate Unique Visit Counter. On the other hand, The code will check if user already exists in the database and if not it will store the user’s Ip and increments the unique visit counter.

In the above code, first attempt is to get the direct IP address of client’s machine, if not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is also not available, then finally get the IP address using REMOTE_ADDR.

The glimpse of the above code is shown in following figure

Unique Visit counter by Storing IP Address using PHP

In this tutorial we have learn how to get IP address of the user to create unique visit counter by using PHP and MySQL.

If you have any doubts regarding to this tutorial feel free to ask in the comment section below.

To catch even more knowledgeable and easy understandable tutorials please subscribe to get email notification.

Download Source Code

1 thought on “Unique Visit counter by Storing IP Address using PHP

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.