Hit Counter 2.0

I should really learn to read things properly. Two pages on in my PHP book was the section on session variables. One of which is the basis for this new, improved, go-faster version of my hit counter. Rather than rely on a number in a flat file, this method actually works by detecting the presence of a session on the client side, which makes a whole lot more sense. Here’s the code:


<?php

 /*hitcounter.php by James Topp
 Version 2.0
 Date: 23 January 2006
 */
 session_start();

 //Get current count
 $count_file="application/hits.txt";
 $count=file_get_contents($count_file);
 if(!isset($_SESSION['started'])) {

	//Increment count
	$count++;

        //Update file
	$fh=fopen($count_file,"w");
	fwrite($fh,$count);
	fclose($fh);

	$_SESSION['started']=true;
 }

 //Create counter display
 $counter="<div id=\"hitcounter\">You are visitor number ".$count." to this site.</div>";
?>

As you can see, the count is only incremented if the $_SESSION['started'] variable is set. This removes the possibility of one or more concurrent sessions pushing the counter up, as the only thing written to the text file is the count itself.

To use this script, copy and paste the code into a text editor and save it as hitcounter.php. Also create a text file containing only the number 0 (or another number if you want to artificially bump your viewing figures up a bit). Save both to a directory called “application” within your site’s root directory. Finally add the following code snippets:

<?php include_once("/application/hitcounter.php"); ?>

(at the very top of each of your pages)

<?php echo $count; ?>

(where you want the count to appear).

And Bob, as they say, is yer mother’s brother.

One Response to “Hit Counter 2.0”

  1. GravatarPaul Fawcus Says:

    Which one is the on button again …………………?
    I managed to do a favicon today (and yet somehow life goes on……)

Leave a Reply





-->