posted on 19 Nov 2002, 15:18; level: Advanced; tool: PHP 3.0;
From: www.webclass.ru
Today I'm going to show you how to make your own unique visitors counter.
There are several ways to build such script: we can store IP addresses and
perform checks/calculations time to time, we can program something for server
environment. And finally the most easy and elegant way is to use cookies.
So our script will store all gathered statistics in MySQL database (the most popular solution).
The table I used in this tutorial is named "stats" and it contains the following fields:
date (DATE), hosts (INT), new (INT), hits (INT)
How does it work...
We will store daily page views, unique visitors and old visitors number.
In the beginning of each page we should perform two tasks:
1.) Read cookie received from browser and update statistics information.
2.) Set cookie, containing current day.
You can see that I named the cookie as tempo, and it contains the current day.
Expiration time was set to until year 2006 but you can choose another value.
When expiration time is reached the visitor will be counted as new one.
Note that you should place your website domain name in the code
above instead of domain.com I used for example.
Let's continue to the next part of our script.
Here we will check cookie and set appropriate sql query.
$tempo = $HTTP_COOKIE_VARS['tempo'];
if (!$tempo){
//new visitor
$sql = 'UPDATE stats SET hosts=hosts+1, new=new+1, hits=hits+1 WHERE date=CURDATE()';
}
else {
if ($tempo != date('d')) {
//old visitor
$sql = 'UPDATE stats SET hosts=hosts+1, hits=hits+1 WHERE date=CURDATE()';
}
else {
//today visitor
$sql = 'UPDATE stats SET hits=hits+1 WHERE date=CURDATE()'
}
}
And finally we should update the database:
MYSQL_CONNECT($hostname, $username, $password) OR DIE('Unable to connect');
@MYSQL_SELECT_DB("$dbName") OR DIE('Unable to select database');
MYSQL_QUERY($sql);
if (!mysql_affected_rows()) {
MYSQL_QUERY("INSERT INTO `stats` (`day` , `hosts` , `new`, `hits`) VALUES (CURDATE(),'0','0','0')");
MYSQL_QUERY($sql);
}
As you can see there is only one sql query is needed to be
executed on each page.
If updating fails (when next day has come) then scirpt inserts new row into the table.
To view statistics gathered you can use phpMyAdmin or you can create
your own script to output table data as explained here.
PHP :
Introduction
Conditions
Loops
Strings
Arrays
Regular Expressions
Date and Time
Objects Three-Tier Atchitectures MySQL and SQL
Basics
Quick Start
Databases, tables, etc...