Skip to main content

A Simple Website Counter Script using PHP

Just the other day, I was asked about how to create a website counter script. Mostly the question is for PHP, so, here, instead of directing you to sophisticated scripts - especially for beginners - we'll show you how to do that in a simple and effective way starting from scratch. To solve this problem, you'll need a place to store your data - visitors no - in some place. Then when someone visit your website, just read the value form the old data and increase by 1 then display the value and replace the value in your storage place. First of all, create a file called count.dat. Open your favorite text editor and create a new PHP class for this purpose and a method to handle the data lets call this file counter.php.
class hitCounter {
//Set a File Name
public $fileName = "count.dat";
  public function getHitCount(){
  //Read the previous value of counter from file
  $counter = intval( trim(file_get_contents($this->fileName)) );
  $counter++;
    //Store the new value in the same file by overwriting it.
  file_put_contents($this->fileName, $counter, LOCK_EX) or die("error");
    return $counter;
   }
}
So, here in this simple hitCounter class, what we have is basically a function that read the file for any old value and increment that by one then store it back. It then return the new value. Save both the count.dat and counter.php files in the same folder. Now, to use this script - say in your home page (index.php) - all you have to do is include the file and create a new instance of the class as follows:
$obj = new hitCounter(); 
$visit = $obj->getHitCount(); 
echo "You're visitor no: " . $visit;
So, now open your home page and you should see that your page increase every time you refresh it. The limitation here is that if a person view your site many times a day your site will keep increasing the value, so, you'll not get a right numbers of visitors in your website. Another limitation is that if the count.dat file is not created beforehand then this script will give an error. In the next section we'll show you how to overcome that. You can use a cookie to know if the person has visited your site before. Then also, add functionality if the data storage file exist or not? To the previous class add the following:
class hitCounter { 
 //Set a File Name
 public $fileName = "count.dat" ;
 
 //Set number of hours a visitor is considered as unique
 public $visitHour = 24;
 
 //Set a cookie name
 public $cookieName = "hitCounter"; 
 
 public function setHitCount(){
  //First Check if file not exist then create one//
  if( !file_exists($this->fileName) ) {
            file_put_contents($this->fileName, '', LOCK_EX) or die("Error: Cant find File");
        }
  //Read the previous value of counter from file
  $counter = intval( trim(file_get_contents($this->fileName)) );  
  
  //Now we check if the visitor is a returning visitor
  if( !isset($_COOKIE[$this->cookieName]) ){
   //Increase the counter
   $counter++;
   
   //Store the new value in the same file by overwriting it.
   file_put_contents($this->fileName, $counter, LOCK_EX) or die("error");
   
   //Set a cookie
   setcookie($this->cookieName, 1, time() + 60 * 60 * $this->visitHour);
  }
 }
 
 public function getHitCount(){
  return intval( trim(file_get_contents($this->fileName)) );
 }  
}
//Let's create an instance of the class
$obj = new hitCounter();
$obj->setHitCount();
Here, we've added a number of hours that a person who visit the website to be considered as a new visitor. Then a cookie name is given. A cookie is a small file that is sent to the user computer and stored there. Every time a user visit the site we can access the cookie and check if it is still exist. So here, we set the time as 24 hours before our cookie expires. You can change this to any value you want. The method setHitCount() now check first if the file exist or not, if not then it create a file. Next the method check if the cookie exist or not? If cookie is not there then the function increment the value of counter and stores it in the file. As, you can see we've added a new method getHitCount() which will just retrieve the value from the file. Now, to set cookie it is always done at the beginning of a document before any HTML content is there. To do that we've created an instance of the class and call the method setHitCount();. Also, you'll need to include this file at the top of your php document. Here, is an example of how to use this class:
<?php
require_once("counter.php");
?>
<!DOCTYPE HTML>
<html>
 <head><title>Counter Test</title></head>
<body>
<?php
 //Write the value of new visitor;
 echo "You're Visitor No: " . $obj->getHitCount();
?>
</body>
</html>
With this simple script I hope you can enhance it more for your needs. Demo of this script can be found here Demo Counter and you can also download the script from here [Download Counter Script]

Comments

Popular posts from this blog

CSS - Styling your Website

CSS – Cascading Style Sheets is a style sheet language used for describing the look and formatting of a document written in a markup language. A CSS is a flexible way to style your pages. In this way you can concentrate on styling and forget about the contents. While someone in you team will take care in generating the contents. Again here, there are some requirement to learn CSS. They are not that different from those of HTML. Basic knowledge of using a personal computer (like creating folders and files, copy, cut, paste, edit). A basic text editor. All personal computers comes with a text editor (like Notepad for Windows, TextEdit in Mac, gedit in Linux with GNOME etc). You can also use other more advanced text editor if you have like Adobe Dream Weaver, or if you prefer the free ones just search online. But a very basic one will do. A browser – All modern PC will come with a browser in build (internet explorer for Windows, Safari for Mac). You can also download a third party brow…

A Simple Login Class Using PHP and MySQL

Login System is always required for any web application that is dynamic. So, this is what actually happened to me. Every website I created, require some form of login system. So, I usually integrate a login system. The problem is that when I update some security features, I've to re-code for all those website. This unique problem, leads me to the creation of this tutorial inspired by the Hashing Security blog.
The idea here is to separate the login system from the rest of the application. The best way to implement this is to use a Login Class and simply integrate the class to any application you design. In this tutorial, I would like to make the login system as secure as possible, hence I would like to ensure a strong encryption of passwords. Now instead of designing my own encryption technique, I'll use a strong and reliable technique described by Crack Station - a Hashing Security blog. Hence before you start download this PasswordHash.php file from GitHub.

This Tutorial …