Simple PHP Hit Counter

Today we are going to Create a PHP Hit Counter. This will be a very simple PHP Script to count Visits on a Page.

This PHP Script is of very few lines. What It does is, reads a file called hit-counter.txt to get Visitor Hits, and updates the file with new Count.

ExampleDownload

Below are the simple steps you have to follow to create this PHP Hit Counter.

Step #1: Create a Text file called hit-counter.txt

Step #2: Create a PHP file called hit-counter.php and Paste the Below Code in it.

<?php

/*
 * Author: Shubham Kumar
 * URL : http://mycodingtricks.com/
 * 
 * It's a Free Script and You can Modify it.
 */

class HitCounter{
    
    //Increment in Count
    private $increment;
    //Hit Counter Text File
    private $file;
    //Return the Hits
    public $hits;
    
    function __construct() {
    	$this->file = __DIR__."/hit-counter.txt";
    	$this->increment = 1;
        $this->HitCounter();
    }
    public function HitCounter(){
        $count = file_get_contents($this->file);
        
        $count += $this->increment;
        
        $this->hits = $count;
        
        file_put_contents($this->file,$count);
    }
}

To make it simple I’ve created a PHP class called HitCounter.

I have created a constructor (Function name same as Class Name) to get the counts. I am using file_get_contens($filename) function to read the Text file and stored it in a variable called $count.

Then, we need to increase the value of the count and Update the Text File.

I have increased the value of Hit Counter by value stored in $increment variable of HitCounter Class and then finally set the $hits variable value and updated the Text File(hit-counter.txt) using the file_put_contents($filename,$string) function.

Step #3: Include the Hit Counter PHP File and Initialize HitCounter Class.

Add the Below code in whatever file you want to count the Hits.

<?php
include 'hit-counter.php';
$hitCounter = new HitCounter();
?>

And Now use the below code to display the Hits.

<?php echo $hitCounter->hits; ?>

For Example: Let’s say you want to show the Visitor Hits count on a index.php file. Then you index.php file will look something like this.

<?php
include 'hit-counter.php';
$hitCounter = new HitCounter();
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Simple PHP Hit Counter Example</title>
    </head>
    <body>
        <h1>Simple PHP Hit Counter Example</h1>
        This page has been visited <strong><?php echo $hitCounter->hits; ?> times</strong>
    </body>
</html>

The above example will look like the below image:

Simple PHP Hit Counter Example
That’s all. Hope you like it and Please don’t forget to share it with your friends on social media/email.

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

You may also like...

Leave a Reply

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