printer friendly version

Simple unique visitors counter

This simple text counter counts today's, yesterday's, total and average visits. I had this avilable as a script for a while, but I decided to turn it into a tutorial, since it's rather easy. In order to complete this tutorial, you need good knowledge of HTML and FTP, FTP client, and host that supports PHP execution. In order to understand how everything works you should also know some PHP basics, but since it's a copy/paste tutorial you can sneak without it.

The counter tracks your visitors based on their IP address. I've seen some tutorials explaining how to count "visits" while they actually count hits. The difference between a hit and a visit is that hit is counted each time page is refreshed. It means if you visit a page 10 times in a single visit, this will count like 10 people visited the page. However, if user's IP is tracked and stored into a database, when he refreshes the page the count will remain the same - because the visitor's IP already exists in our database. Some people have dynamic IPs, but this is okay since it changes every time they reconnect, which can be once a day or so - the unique count can still be trusted.

Okay, now if you're ready, let's get to work.

1st file: empty index

Make an empty file and name it index.html. Save it in a folder named counter. This will prevent other people from nosing around your counter folder.

2nd file: IP database

Make an empty file and name it ip.db. The extension does not matter, but .db will prevent browsers from opening it as they would a normal text file. This is the file where visitors' IPs will be stored. Save it in the folder counter as well.

3rd file: count database

This file should contain a set of zeros as following:

0%0%0%0000 00 00%0

The first zero represents today's count. The second zero is yesterday's count. The third zero is a total count. Next 8 zeroes is today's date, while the last zero says for how many days has the script been working. These values will change on script execution, so leave them as they are - name this file count.db and save it in the counter folder.

If your website is online for quite a while and you used some free counter I'm sure you'd like to keep that number. You can replace the third zero with the total visitor count. However, you'll also need to replace the last number with the number of days you used the script for, otherwise your average statistics won't be correct.

4th file: counter display

In order to make things easier to understand, I will first show you the easier of the two scripts. Make a new file and name it showcounter.php. This file will open our count database and display statistics. Copy the following code to your file:

<table>
<tr>
<th colspan="2">Unique visitors</th>
</tr>
<tr>
<td><b>Today</b></td>
<td>
<?php
$file_count = fopen('counter/count.db', 'rb');
	$data = '';
	while (!feof($file_count)) $data .= fread($file_count, 4096);
	fclose($file_count);
	list($today, $yesterday, $total, $date, $days) = split("%", $data);
	echo $today;
?>
</td>
</tr>
<tr>
<td><b>Yesterday</b></td>
<td>
<?php
	echo $yesterday;
?>
</td>
</tr>
<tr>
<td><b>Total</b></td>
<td>
<?php
	echo $total;
?>
</td>
</tr>
<tr>
<td><b>Daily average</b></td>
<td>
<?php
	echo ceil($total/$days);
?>
</td>
</tr>
</table>

Here we have a table - in the first row, table header, is the text Unique visitors - I'm sure you understand that much HTML. Then, we have words Today, Yesterday, Total, Daily average in the left column, and the numeric values will be shown in the right column. That's about it - not really fancy looking, but you can style it with CSS.

Now the PHP part. In line 9 the file count.db from folder counter opens with the read permission. This means file is opened for reading only. Then the empty variable $data is filled with information from that file, one character at the time. The number 4096 is max number of bytes to read from the file, but you should just leave this number as is. When all data is read, the file is closed and the data is separated into 5 variables (line 13) using % as delimiter.

Once we have 5 values in 5 variables, it's simple - each variable's value is displayed using the echo function. I hope you understood what this scripts does, and if you didn't - just copy/paste this code, it will work. Save this file in the folder counter.

5th file: counter script

This is a working script that will do everything. Make a new file and name it counter.php. Save it in the counter folder with all the other files you made so far. The code to be copied is this:

<?php
	$ip = $_SERVER['REMOTE_ADDR'];
	
	$file_ip = fopen('counter/ip.db', 'rb');
	while (!feof($file_ip)) $line[]=fgets($file_ip,1024);
	for ($i=0; $i<(count($line)); $i++) {
		list($ip_x) = split("\n",$line[$i]);
		if ($ip == $ip_x) {$found = 1;}
	}
	fclose($file_ip);
	
	if (!($found==1)) {
		$file_ip2 = fopen('counter/ip.db', 'ab');
		$line = "$ip\n";
		fwrite($file_ip2, $line, strlen($line));
		$file_count = fopen('counter/count.db', 'rb');
		$data = '';
		while (!feof($file_count)) $data .= fread($file_count, 4096);
		fclose($file_count);
		list($today, $yesterday, $total, $date, $days) = split("%", $data);
		if ($date == date("Y m d")) $today++;
			else {
				$yesterday = $today;
				$today = 1;
				$days++;
				$date = date("Y m d");
			}
		$total++;
		$line = "$today%$yesterday%$total%$date%$days";
		
		$file_count2 = fopen('counter/count.db', 'wb');
		fwrite($file_count2, $line, strlen($line));
		fclose($file_count2);
		fclose($file_ip2);
	}
?>

Uh. I wrote this script a long time ago but I'll try to explain it the best I can. Second line is self-explanatory, remote addres or IP is stored in the variable $ip. Then the file with IPs is opened and each line of this file is read into an array. for() loop goes through this array and compares the IP with stored ones - if the exact IP is found, the variable $found gets a value of 1.

After the IP has been checked, if it's not found in the database it means the visitor is here for the first time, and his IP will be added to the database. Then, today's and total count will be increased. In case today's date does not match the date in the count database, today's count becomes yesterday's count, the number of days increases, and the date changes to today's date.

In the end all variables are written into database opened for writing. I know this script has many different file variables, but this is because we have to open a file separately for reading and writing. I really hope you understand how this works -_-;

Making it work

If you did everything exactly as suggested in this tutorial, you have 5 files in your folder named counter. This folder should be inside your site root. To make the counter work, you have to include the scripts in your site pages - if you use dynamic inclusion, you will only have to include the counter in your main file, index.php. If you don't, you'll have to include it in each file, or in some file that is included to all your pages, something like header.php or navigation.php or whatever it is you are including. This is how to include the counter:

<?php include 'counter/counter.php'; ?>

Counter will be invisible, but it will work. To make your statistics visible, paste this code where you want the counter to appear:

<?php include 'counter/showcounter.php'; ?>

Now you have linked everything, it's time to test it on your server.

I hope you know how to use a FTP client, because I'm not into explaining it again. Upload the entire folder with counter scripts and data to your root folder. Also, upload the modified files where you included the script. Then, enter the folder counter and CHMOD files count.db and ip.db to 666 (rw-rw-rw-). You're done.

Go to your page where statistics are shown (the page where you included showcounter.php) and there should be a number 1 (or higher) for today, and zero for yesterday. If you don't see the counter where you expected, then you did something wrong - follow this tutorial once again and be careful about every little detail - this script is on my site for months and it's working without any flaws, so it should work for you too.

In case this tutorial was too hard for you to follow, you can download all files here.

Quick links

More of my work

Follow me on Twitter
RSS feeds

Affiliates

A List Apart Survey 2009

In obscuro — dark art and resources © 2004-2010 Nela Dunato. Terms of use

Back to top