Tag Archives: php

Designing a basic php counter for your website

I think you may have noticed on several websites, a line in the footer saying "You are visitor no. ..." or something on similar lines or maybe something humorous like "You are jobless no. ...". The number displayed is the value of a dynamic counter which keeps increasing each time that page is being fetched from the server.

You can easily install such counters using the code provided by several websites like http://www.simplehitcounter.com/ , http://www.website-hit-counters.com/ etc. which give you an option to specify the design, font and initial value of the counter. However, if you like building code from scratch, you can design your own basic php counter.  All you need is that your website hosting server should support php scripts.

The logic behind this counter implementation can be explained in 3 steps.

  1. Read the current value of counter from a file on server side.
  2. Increment the current value and store it back in the same file
  3. Display this value using the formatting as you want.

Here's the php code for this counter:

<?php
$myFile = "resources/visitors_count.txt";
if(file_exists($myFile))
{
 $fh = fopen($myFile, 'r');
 $size = filesize($myFile);
 if($size>0)
 {
 $count = fread($fh, $size);
 }
 else {
 $count = 0;
 }
 fclose($fh);
 $fh = fopen($myFile, 'w') or die("can't open file");
 $count++;
 fwrite($fh, $count);
 fclose($fh);
}
else {
 $fh = fopen($myFile, 'w') or die("can't open file");
 $count=1;
 fwrite($fh, $count);
 fclose($fh);
}
$display_string = "You are visitor no. ". $count;
echo "<em> <span style='color:blue'> $display_string </span></em>";
?>

The point to be taken care of is that you must have the appropriate permissions to access the file containing counter value on server side. Change the permissions of that file to 644 or 755, if it's not already that.

Now, installing this counter in your website is simple. You just need to add this line <?php include "count.php" ?> to the place on your website where you want to display the count. Another thing to note is that this code will work only if the file where you are pasting this code has .php extension or another equivalent extension which makes the server realize that it is a php script. For example, I am using this counter to keep track of visitors on my website's main page. If you don't want to display the visitors count on your website but would like to keep track of visitors coming to your website, you can comment out the echo statement in the code above.

You can download this php script from here.