PHP Website Hit Counter

From NippAero

Jump to: navigation, search

I get asked a lot about my website and how I create things. One of the question I got recently was how I log the number of website visits. Well, without getting all technical I use the Google analytics tools to keep statistical data about the number of visits and history. It is a very good product and is free. To display a simple hit counter on my page I use a simple PHP/MySQL script to log the number of visits and display them on my page. This is not meant to be an all in one super duper meet all your needs way of tracking users. I only use it mostly for looks on my main page.

Contents

MySQL Version

This version of my counter script logs visits into a table in MySQL. It is a very simple table with two fields. Some people do not have access to a MySQL database so I'll get around to posting a flat file version of the script soon.

Requirements

  • MySQL Database
  • PHP Configured with MySQL module

Setup

Upload the Images

You will need a set of jpeg or gif images 1 thru 9 plus 0. These will be used to display the counter image. You can use mine or find some others. Upload them to your web server directory and set the image_dir variable in the php script.

Image:0.jpgImage:1.jpgImage:2.jpgImage:3.jpgImage:4.jpgImage:5.jpgImage:6.jpgImage:7.jpgImage:8.jpgImage:9.jpg

Create MySQL Table

CREATE TABLE `counter` (
  `id` mediumint(9) NOT NULL auto_increment,
  `count` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

Counter.inc.php

This is an example. You could obviously handle your database connections and session handling different but you get the idea.

<?php
/**
 *  counter.inc.php
 *  Copyright (C) 2008 Mike Nipp
 *
 *  The counter include is used to keep track of the number
 *  of visitors to the website. It is very simple using a 
 *  MySQL table to increment the count. It is not practical
 *  to add 1 to the counter every time someone accesses the
 *  page. The counters would not be very accurate. So I
 *  decided to track the users PHP session to try to keep
 *  track of each unique user.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it as you wish.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY.
 *
 */

session_start(); //Kick off the session

/**
 * Database Constants - these constants are required
 * in order for there to be a successful connection
 * to the MySQL database.
 */
define("DB_SERVER", "localhost");	//name of the mysql server
define("DB_USER", "user");		//name of user to access the database  
define("DB_PASS", "password");		//password for the user above
define("DB_NAME", "mydb");		//name of database

$image_dir = "imgages"; //directory where the images can be found.

// Connect to the database
mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die('Unable to connect to database! Please try again later.');
mysql_select_db(DB_NAME) or die(mysql_())

    //Simple function to increment the number of users in the db table
    function incrementCounter(){
       $sql = "UPDATE counter SET count=(count + 1) WHERE id=1";
       mysql_query($sql);
    }
	
    //Simple function to lookup the number of visitors in the database
    function getCount(){
       $sql = "SELECT count FROM counter WHERE id = 1";
       mysql_query($sql);
       $result = mysql_query($sql) or die('Error, db query failed');
       $hits = trim(mysql_result($result, 0, 'count'));
       return $hits;
    }

$img_alt = 'alt=""';
//If this is the first time the user has visited there will be no PHP
//session variables registered so we increment the counter by 1 by 
//calling the incrementCounter function.
if (!session_is_registered("counted")){
 incrementCounter();
}

//Now we register the variable in the users PHP session so he wont be counted again 
session_register("counted");

//The magic happens here. Replacing the database string with the images.
$hits = getCount();
$hits = "<a href='http://www.nippaero.com'>".$hits;
$hits = str_replace("0","<img src='$image_dir/0.jpg' $img_alt>","$hits");
$hits = str_replace("1","<img src='$image_dir/1.jpg' $img_alt>","$hits");
$hits = str_replace("2","<img src='$image_dir/2.jpg' $img_alt>","$hits");
$hits = str_replace("3","<img src='$image_dir/3.jpg' $img_alt>","$hits");
$hits = str_replace("4","<img src='$image_dir/4.jpg' $img_alt>","$hits");
$hits = str_replace("5","<img src='$image_dir/5.jpg' $img_alt>","$hits");
$hits = str_replace("6","<img src='$image_dir/6.jpg' $img_alt>","$hits");
$hits = str_replace("7","<img src='$image_dir/7.jpg' $img_alt>","$hits");
$hits = str_replace("8","<img src='$image_dir/8.jpg' $img_alt>","$hits");
$hits = str_replace("9","<img src='$image_dir/9.jpg' $img_alt>","$hits");
$hits = $hits."</a>";
$hits = str_replace('alt=""','alt="" border="0" height="12" width="10"',$hits);

?>

Displaying the counter

You can display the counter anywhere in your page by putting the following code in your document.

<? echo $hits; ?>

Flat File Version

No MySQL database needed.

Coming soon...

Requirements