Write a simple PHP Hit Counter Script

By | October 29, 2011

In this tutorial, I am going to show you a simple way to write a Hit Counter script in PHP to save and display the number of visits to your website.

We will basically store and increment the hits in a file, that can be used to display the total hit count as well.

The code to store the hits follows -

<?php

class BT_HitCounter {

	// Show "unique" visits only ?
	public $unique_visits = false;

	// Number of hours a visitor is considered as "unique"
	public $unique_hours = 24;

	// Directory to write to (without any trailing slashes)
	public $hit_count_dir = 'hitcount';

	// File to write to
	public $hit_count_file = 'hitcount.txt';

	// Cookie Name
	public $cookie_name = 'bt_hit_count';

	// Record HIT
	public function recordHit() {

		// Check whether the target dir exists or not. If not, then create it.
		if ( isset($this->hit_count_dir) && strlen($this->hit_count_dir) > 0 ) {

			if( !file_exists($this->hit_count_dir) ) {
				mkdir($hit_count_dir/*, 0777, TRUE*/) or die('ERROR: Could not create the specified directory!');  // http://php.net/mkdir
			}

		}

		$hit_count_file = $this->hit_count_dir . '/' . $this->hit_count_file;

		// Check whether the target file exists or not. If not, then create it.
		if( !file_exists($hit_count_file) ) {
			file_put_contents($hit_count_file, '', LOCK_EX) or die("ERROR: Can't write to "$hit_count_file", please make sure that your path is correct and you have appropriate permissions on the target directory and/or file!");
		}

		// Get current count from file
		$hit_count = intval( trim(file_get_contents($hit_count_file)) );

		if ( !$this->unique_visits || !isset($_COOKIE[$this->cookie_name]) ) {

			// Increment the hit count by 1 and write to the file
			$hit_count++;
			file_put_contents($hit_count_file, $hit_count, LOCK_EX) or die("ERROR: Can't write to "$hit_count_file", please make sure that your path is correct and you have appropriate permissions on the target directory and/or file!");

			if( $this->unique_visits ) {
				// Send a cookie to the visitor (to track him) along with the P3P compact privacy policy
				header('P3P: CP="NOI NID"');
				setcookie($cookie_name, 1, time() + 60 * 60 * $unique_hours);
			}

		}

	} // End of Method
	
	// Get Total HITs
	public function getHitCount() {
		$hit_count_file = $this->hit_count_dir . '/' . $this->hit_count_file;

		// Get current count from file
		return (int) trim(file_get_contents($hit_count_file));
	} // End of Method

} // End of Class

$hit_obj = new BT_HitCounter();
// $hit_obj->unique_visits = true;
$hit_obj->recordHit();

The script above basically creates the target directory and the file to which the hits needs to be stored is created (if they do not exist) and if there is a failure then the script exits with an error message. Then the value from the file is taken, incremented by 1 and stored back in the file using file_get_contents and file_put_contents.

If we want to count "unique" visits instead of overall hits, then we will just have to set the $unique_visits property of the class to true and that will basically set a cookie to track the visitor who has already open the page in the browser once. the $unique_hours property controls the hours for which a particular user is considered to be "unique".

Now, you just need to load the file in your PHP codebase -

<?php
require 'hit_counter.php';
// ... Other Code ...

Displaying the Hits from the file is fairly easy using the Class.

...
echo $hit_obj->getHitCount();
...

Tracking Hits for different pages can be accomplished by using some relevant value from $_REQUEST or the Database to create unique files and cookies (cookie name).

You can even use a Relational Database like Sqlite or MySQL to track the hits and store other information of the visitors like IP Address, User Agent, Visit Date and Time, which page they have visited, etc.

Final Thoughts

Although this was a quick and simple solution to the requirement, there are other great tools/services like Google Analytics and Piwik that provides us with "much" more features, analytics, reports, charts and information about the visitors to our website or application.

Let me know about your thoughts in comments!

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

2 Comments

Write a simple PHP Hit Counter Script
  1. Nnadozie Diala

    wonderful tutorial, I have only one question with how the cookies work, it’s not very clear. I keep getting the errors:

    Undefined variable: unique_hours

    Undefined variable: cookie_name

Leave a Reply

Your email address will not be published. Required fields are marked *