The Coder

Basic Hit Counter

Original posted by: Admin on 21-01-2007

Most sites now days have hit counters. They are a good way of keeping track the amount of people that have visited your site. Their are many free hit counters out their but most of them are marked with their own distinct branding... So how about try building your own.

First of all you will need to create a table in your database.


CREATE TABLE `hit_counter` (
`hit_id` INT( 8 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`hit_time` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)


Now that the database has a the correct table in it we will use the mySQL class to insert and read the relevant entries.

On the bottom of each page place the following code, it will insert a new row for the visitor and then display the total hits on your site.


<?php
//Create mySQL Class
$mySQL = new mySQL();

//Insert new row
$mySQL -> writeDB('INSERT INTO `hit_counter` (`hit_time`) VALUES (NOW())');

//Print out total hits
$data = $mySQL -> readDB('SELECT MAX( `hit_id` ) as max_id FROM `hit_counter` WHERE 1 =1');
echo $data[0]['max_id`];
?>


The counter is now working, but lets display it as an image instead of text.

Create a page called hit_counter.php and fill it with the following code


<?php
//Include the mySQL Class
require_once('sqlclass.php');

//Record Visit
$mySQL -> writeDB('INSERT INTO `hit_counter` (`hit_time`) VALUES (NOW())');

//Get Visit Number
$data = $mySQL -> readDB('SELECT MAX( `hit_id` ) as max_id FROM `hit_counter` WHERE 1 =1');

//Define the header (Image output PNG)
header("Content-type: image/png");

//Define the width & height of the image
$width=200;
$height=50;

//Create the image
$image = imagecreate($width, $height);

//Create a background colour, I have gone with white
$back = imagecolorallocate($image, 255, 255, 255);

//Fill the image with that colour
imagefill($image, 0, 0, $back);

//Generate the text colour, I've gone with black
$textcolour = imagecolorallocate($image, 0, 0, 0);

//Print the random number with a random font
imagestring($image, 5, 10, 10, $data[0]['max_id'], $textcolour);

//Display the image
imagepng($image);

//Destory the image data
imagedestroy($image);

?>


Now to view your image all you have to do is call the hit_counter.php within an img tag.

<img src="hit_counter.php" />

The PHP file will do everything, this is a great little way to add a hit counter to your myspace profile or any of your web site pages.

Example




Login to make a comment 0 Comments Found