Creating a Unique hit counter in PHP

Creating a Unique hit counter in PHP
Creating a Unique hit counter in PHP

Topic – 52
Creating a Unique hit counter in PHP
Part – 3

images-1-300x123-300x1234-300x123

DOC,PDF

-In last part we discussed about the logic for counting the users and saving their ip address.
-Here in this part we are going to implement the whole logic for Unique hit counter.
-Whenever a new user accesses the file (count.php) then the current user ip address is going to be saved in ip.txt and the value in count.txt is going to be incremented by 1.
If the user is accessing the file second time or more, then the counting and saving the ip address will be skipped.
Program:
<?php
function hit_counter(){
$ip_address = $_SERVER[‘REMOTE_ADDR’];
$ip_file = file(‘ip.txt’);
foreach($ip_file as $ip){
$ip_single = trim($ip).'<br>’;

if($ip_address == $ip_single){
echo $found = true;
echo “Found”;
break;
}
else{
$found = false;
echo “Not Found”;
}
}
if(!$found){

$filename =”count.txt”;
$handle = fopen($filename,’r’);
$current = fread($handle,filesize($filename));
fclose($handle);

$current = $current + 1;
$handle = fopen($filename,’w’);
fwrite($handle,$current);
fclose($handle);

$filename = “ip.txt”;
$handle = fopen($filename,’a’);
fwrite($handle,”$ip_address”.”\n”);
fclose($handle);
}
$ip_file = file(‘ip.txt’);
foreach($ip_file as $ip){
echo $ip_single = $ip.'<br>’;
}
}
hit_counter();
?>
php52_3
Output::(Here we are running php in local host)
//count.txt
1
//ip.txt
127.0.0.1

-When user access the file count.php then ip address of the current user is going to be stored in $ip_address variable.
-ip addresses in the ip.txt file are going to iterated by foreach() loop and each ip address in the ip.txt file is going to be saved in $ip_single variable. For each iteration $ip_single value is stored with single ip address and this variable is compared with $ip_address variable in if loop and if the condition satisfies then the counting and saving ip address will not be done.
-If the condition in the loop does not satisfy then count will be incremented by one and the ip address will be saved.
-In above program we are writing the logic outside for each loop in other if statement for counting and saving the ip address instead of writing in else statement.

-Here we are restricting the count is unique for the user.
-we are counting the users when the file(count.php) is accessed but not the number of times users accessed the file.
-we are updating the count by one whenever a new user accesses the file.
-So we created a file based unique hit counter.

images-1-300x123-300x1234-300x123

DOC,PDF

Leave a Reply