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.

CREATE TABLE `counter` (
  `visiters` int(255) NOT NULL,
  `id` int(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `ipdb` (
  `ip` text NOT NULL,
  `id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

ALTER TABLE `ipdb`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `ipdb`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;COMMIT;

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.

INSERT INTO `counter` (`visiters`, `id`) VALUES
(1, 0);
COMMIT;

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

<?php
$con = mysqli_connect("localhost","root","","technopoints");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

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.

<!DOCTYPE html>
<html lang="en">
<head>
<style>
  body {
  background: #8c8900;
  color: #fff;
  font-size: 22px;
}
span {
  display: inline-block;
  padding: 6px 6px 4px;
  border-radius: 3px;
  background: #5a9671;
  margin-right: -2px;
}
.center {
  text-align: center;
  width: 50%;
  margin: 20px auto;
}
.message {
  color: #ccc6e3;
  font-family: Verdana;
  font-size: 12px;
}
.img1 {
    display: block;
    margin-left: auto;
    margin-right: auto;
}
  </style>
</head>
<body><center><br><br><br>
<?php function getUserIpAddr(){
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        //ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        //ip pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
echo 'User Real IP - '.getUserIpAddr();
 $ip = getUserIpAddr();
 echo "<br>";
?>
  <?php
		include 'dbconfig.php';
		$qry = "SELECT * FROM `ipdb` WHERE `ip` = '$ip'";
		$result = mysqli_query($con,$qry);
		$num = mysqli_num_rows($result);
		if ($num == 0){
			$qry3 = "INSERT INTO `ipdb`(`ip`) VALUES ('$ip')";
			mysqli_query($con,$qry3);
			//echo "new ip register";	
			$qry1 = "SELECT * FROM `counter` WHERE `id` = 0";
			$result1 = mysqli_query($con,$qry1);
			$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
			$count = $row1['visiters'];
			$count = $count + 1;
			//echo "<br>";
			//echo "number of unique visiters is $count";
			$qry2 = "UPDATE `counter` SET `visiters`='$count' WHERE `id`=0";
			$result2=mysqli_query($con,$qry2);
}else{
			$qry1 = "SELECT * FROM `counter` WHERE `id` = 0";
			$result1 = mysqli_query($con,$qry1);
			$row1 = mysqli_fetch_array($result1, MYSQLI_ASSOC);
			$count = $row1['visiters'];
			//echo "<br>";
			//echo "number of unique visiters is $count";
}
  ?>
  <?php
$numlength = strlen((string)$count); ?>
<br><h3>Unique Visit Counter</h3><?php $count; 
 $stri = (string)$count;?>
This value Shows Unique Visit Count</center>
  <body/>
  </html>

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

2 thoughts 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.