how to Make a PHP Based Hit Counter

Write your "How To" regarding anything you are comfortable with and you feel it will help the forum members.

NOTE :: All threads started here will appear only after the approval from Administrator
Post Reply
anish
Posts: 353
Joined: Fri Apr 27, 2007 12:34 pm
Contact:

how to Make a PHP Based Hit Counter

Post by anish »

websaint recently posted a PHP hit counter using a flat-file to store information.

This is a guide a wrote a little while ago - it was for another web site, but I'll post it here as well.

-----------------------------------------------------------------------------------

First and foremost, you need to create a new table. You can use a whole new database if you want (and assuming you have one free), but it's a bit of a waste.

For this guide, our table will be called 'hits', and will contain two fields - 'unique' and 'total'. The first field, 'unique', will log all unique visits/hits to the site. And 'total' will log all visits to the site, unique or not. You can do this from within PHP:
[PHP]mysql_query("CREATE TABLE hits (unique int(6), total int(7))");[/PHP]
Or just go directly through MySQL:
[PHP]CREATE TABLE hits (unique int(6), total int(7));[/PHP]

Now obviously, you can change the buffer size around if you want, depending on how active you are expecting your site to be. In this example, the field 'unique' can contain any number up to 6 digits long - that is to say, any number from 0 to 100,000, and 'total' can store up to 7 digits in one entry. The average person that is reading this and is interested in creating a counter from it is not going to be having astronomical numbers of hits to their site, so what I've used is probobly a bit of overkill.

After you've created a table, you need to construct a script that will log data to the table.

Because we are wanting to log unique hits, hte use of cookies is required. This obviously doesn't work for all users, but letting a few slip through the nets shouldn't really damage things.
[PHP]<?php
// Assumes: you are already connected to MySQL,
// and have selected the database you will be using;
// That the visitor is cookie-compatible;
// That the visitor has not cleared their cookies.


// Also note that this script is very optimizable.
// It is intended only to work and to be easy to understand,
// not to win any awards.

$result = mysql_query("SELECT * FROM hits");
$data = mysql_fetch_assoc($result);
$total_hits = $data['total'];
$unique_hits = $data['unique'];
// Firstly, grab the existing data from MySQL


$total_hits++;
mysql_query("UPDATE hits SET total = '" . $total_hits . "'");
// The total number of hits is going to be incremented
// regardless of the situation, so this can be done first
// to get it out of the way


if(isset($_COOKIE['visited'])) {
$cookie = $_COOKIE['visited'];
// Our global variable index will be called 'visited',
// to make it easy to remember
} else {
$cookie = false;
}

if(!$cookie) {
$unique_hits++;
mysql_query("UPDATE hits SET unique = '" . $unique_hits . "'");
// The value of $cookie is NOT true, meaning that the user
// has not yet been counted
} else {
setcookie("visited","1",time()+86400,"/");
// Now, we set the cookie's value. Here, it is set to
// expire in 86,400 seconds (24 hours) - you can
// change this is if you like, but it ensures that the
// same person won't be counted as a unique visitor
// more than once in a 24-hour period
}

mysql_free_result($result);
mysql_close();

?>
[/PHP]
And there we have it - a fully functional hit-counting script. Now all you would need to do is save the file somewhere, and use:
[PHP]<?php include("script-path.php"); ?>
[/PHP]
Now, what if you want to retrieve the number of hits your site has received, so you can display it somewhere?

This is very easy to achieve. Here are a couple of custom-coded functions that'll do it for you:
[PHP]// Assumes: You are connected to MySQL
// and have selected the database
// (eg. mysql_connect(), mysql_select_db())

function UniqueHits() {
$result = mysql_query("SELECT unique FROM hits");
$data = mysql_fetch_assoc($result);
$unique_hits = $data['unique'];
mysql_free_result($result);
return $unique_hits;
}

function TotalHits() {
$result = mysql_query("SELECT total FROM hits");
$data = mysql_fetch_assoc($result);
$total_hits = $data['total'];
mysql_free_result($result);
return $total;
}
[/PHP]
Now, you could put that in a second script, and include a reference to it as well - but it would just be much easier all around to add it to the end of the other script (before the ?>).

Now all you have to do is:
[PHP]echo UniqueHits();
// OR
echo TotalHits();

[/PHP]

In order to use them.

-----------------------------------------------------------------------------------

Review:
Our MySQL table was named 'hits', and was created with:
CREATE TABLE hits (unique int(6), total int(7));

The final script was, including everything, was:
[PHP]<?php
// Assumes: you are already connected to MySQL,
// and have selected the database you will be using;
// That the visitor is cookie-compatible;
// That the visitor has not cleared their cookies.


// Also note that this script is very optimizable.
// It is intended only to work and to be easy to understand,
// not to win any awards.

$result = mysql_query("SELECT * FROM hits");
$data = mysql_fetch_assoc($result);
$total_hits = $data['total'];
$unique_hits = $data['unique'];
// Firstly, grab the existing data from MySQL


$total_hits++;
mysql_query("UPDATE hits SET total = '" . $total_hits . "'");
// The total number of hits is going to be incremented
// regardless of the situation, so this can be done first
// to get it out of the way


if(isset($_COOKIE['visited'])) {
$cookie = $_COOKIE['visited'];
// Our global variable index will be called 'visited',
// to make it easy to remember
} else {
$cookie = false;
}

if(!$cookie) {
$unique_hits++;
mysql_query("UPDATE hits SET unique = '" . $unique_hits . "'");
// The value of $cookie is NOT true, meaning that the user
// has not yet been counted
} else {
setcookie("visited","1",time()+86400,"/");
// Now, we set the cookie's value. Here, it is set to
// expire in 86,400 seconds (24 hours) - you can
// change this is if you like, but it ensures that the
// same person won't be counted as a unique visitor
// more than once in a 24-hour period
}

mysql_free_result($result);

function UniqueHits() {
$result = mysql_query("SELECT unique FROM hits");
$data = mysql_fetch_assoc($result);
$unique_hits = $data['unique'];
mysql_free_result($result);
return $unique_hits;
}

function TotalHits() {
$result = mysql_query("SELECT total FROM hits");
$data = mysql_fetch_assoc($result);
$total_hits = $data['total'];
mysql_free_result($result);
return $total;
}

mysql_close();

?>
[/PHP]
And there we have it. A fully functional, ready-to-go, PHP hit-counting script that not only logs page views, but also unique visits to your site.

Notes:
-- All coding is done by me. As such, it is done in my own style, meaning that you might not like it.
-- This script was written 'on-the-fly' while I was writing this quick guide, and it hasn't yet been tested at all. It might contain a bug or syntax error or two.

Anish


CryptWizard
Posts: 4
Joined: Sat Apr 28, 2007 8:44 am

Post by CryptWizard »

I perfer to use a flat file for something as simple as a hit counter. The performance is much better.
Post Reply