Home » Programming / Coding

Php Visitor Counter File Based

27 August 2009 1,379 views No Comment

I am  not a Php programmer, these days I work with Asp .Net. However I used to work with Php in the past, and that gives me some edge working with simple php stuffs these days for clients, in case I need to.

One of my clients asked to do a visitor counter for them. Looking at the options it could be done in many ways e.g. file based, mySql based etc. To keep it simple I developed a file based version of the visitor counter for the client.

We had to make sure that only one visitor visit is counted for each visit to the website, and counter does not increase count for every page visit.

Here is the scenario how it works:

  • The counter is placed on an include file which is used by all the pages, this way we can make sure that only one count per visitor visit is logged in the counter. I have put it on footer.php include file. Also we can have the counter working from any page no matter which page user first lands in on the website.
  • User lands on any page on the website.
  • Read the current count from the counter file.
  • We check if the counter session is set.
  • If the counter session is set, we do nothing but show the current visitor count.
  • If the counter session is not set we create a new session, increase the count by 1 and then write it back to the counter file.

How it works:

Make a text file hitcounter.txt and make sure it have write permission.

Make an include file for the counter called counter.php. Here is the code for that.

<?php
session_start();
$count_my_page = (“hitcounter.txt”);
$hits = file($count_my_page);
if( !isset($_SESSION['last_access']) )
{
$_SESSION['last_access'] = time();
$hits[0] ++;
$fp = fopen($count_my_page , “w”);
fputs($fp , “$hits[0]“);
fclose($fp);
}
echo $hits[0];
?>

Now all that left is calling this include file from the footer include file. Here is the code that just does that:

You Are Visitor #:&nbsp;</b><?php include (“includes/counter.php”); ?>

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.