Return to Portfolio

Unique Hit Counter

Script Last Updated: Friday, August 7th, 2009
Documentation Last Updated: Thursday, November 10th, 2011

The Script

Download this script

This is a script that will output to the screen where included the number of unique visitors to the page it was included in. It is also the same hit counter you see at the bottom of this page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
// Before using:
// Create a directory to store hits and set its permissions to 777
// To use:
/* <?php include "include.unique_hit_counter.php"; ?> */

// File path for storing hits data
$file_path = '/files/';
// Build filename
$counter_file = getcwd().$file_path.md5($_SERVER['SCRIPT_NAME']).".txt";
// Get data to be stored
$user_ip = $_SERVER['REMOTE_ADDR'];
$ctime = time();
// Build storage variables
$ip_array  = array();
$count = 0;
// If data file exists extract hits
if(file_exists($counter_file)) {
    $content = file_get_contents($counter_file);
    $info = unserialize($content);
    
    $count = count($info);
    
    foreach($info as $entry) {
        list($ip, $time) = $entry;
        $ip_array[] = $ip;
    } 
}
// Verify that the visitor is new
$unique = !in_array($user_ip, $ip_array);
// If the visitor is unique, add their hit to the data file
if($unique) {
    $ip_array[] = $user_ip;
    $info[] = array($user_ip, $ctime);
    
    $count++;

    $file = fopen($counter_file, 'w');
    fwrite($file, serialize($info));
    fclose($file);
}
// Echo the hit count
echo $count;
?>

Usage Examples

The following is an example of how to use this script.

1
2
// This line will output the number of unique hits
include "include.unique_hit_counter.php";

386 Unique Visitors