How to create a page hit counter in PHP
Article Metadata
This article explains how to create a web page hit counter in PHP
Contents |
Introduction
Web pages count visitors, page views basically two ways. The first is a non-unique page view/visit method and the second is an unique page view/visit method, we will have a closer look how to implement the latter one in this example.
User IP address will be recorded, even though they do vary we get much more accurate estimate.
Prerequisites
- PHP support. localhost or remote server (this example is tested with PHP v 5.4 installed).
- Code editor of your choise.
Example code
For this example we need the following files. You can create empty templates in your code editor for this.
-index.php
-ipaddr.txt IP addresses to be stored by every visit.
-visitcounter.php Called from the index.php each time. Grabs the user's IP address.
-visitlog.txt
To check whether an IP address is already stored, we need to check for doubles.
visitcounter.php
This file will first contain a function called count_hit(), which is everytime called from the index.php file.
The user's IP address will be grabbed by the environmental information of the user 'REMOTE_ADDR'.
Note: There is a bit more accurate method to determine the user's IP address, but this example uses the REMOTE_ADDR for demonstration purposes.
The count_hit() function is to check if the grabbed IP address is NOT already included in the log file of IP addresses. The file "visitlog.txt" will be opened in this case. The $ip_file forms an array, each line of the file will be an item in the array. This array will then be gone thru each element at a time. You can add three lines of random ip addresses for the visitlog.txt file to test the procedure out before real ip addresses are fetched. During the loop if the grabbed ip is found then if not this states if the counter is increased or not.
<?php
count_hit() {
$ip_address = $_SERVER['REMOTE_ADDR '];
$visit_ip_file = file('visitlog.txt');
foreach($visit_ip_file as $ip) {
// echo trim ($ip).','; -- for debugging purposes
$ip_item = trim($ip);
if ($ip_address==$ip_item) {
$found_ip = true;
break;
} else {
$found_ip = false;
}
}
if ($found_ip==false) {
$filename = 'viewcount.txt';
$handle = fopen($filename, 'r');
$current = fread($handle, filesize($filename));
echo $current; // for debugging - current value in counter
fclose($handle);
$current_inc = $current + 1;
$handle = fopen($filename, 'w');
fwrite($handle, $current_inc);
fclose($handle);
$handle = fopen('ipaddr.txt', 'a');
fwrite($handle, $ip_address."\n");
fclose($handle);
}
}
?>
index.php
The visitcounter.php file is included here first.
<?php
include 'visitcounter.php';
?>
visitlog.txt
In this file the initial number will be set to plain zero "0".
ipaddr.txt
In this file there is nothing yet, so it is currently empty.
Tested with
PHP 5.4


(no comments yet)