2019-02-10 Pujan Niroula 1 Minute(s) Read

Create Simple Pageview Counter in PHP

img-thumb pageview counter php.jpg

Some website owner wants to display total pageviews on their web so far. This gives visitor an impression, a psychological impression. If you also want to display total pageviews on your website then this post is for you man :)

In this tutorial I will use just a file (pageview.txt) to store total pageview. I used some PHP's inbuilt functions such as file_get_contents() and file_put_contents().

Simple Pageview Counter with PHP - Source Code

<?php
class pageView
{
    //Declear file to store total pageview count
    private $file = 'pageview.txt';

    function __construct(){
        if(!file_exists($this->file)) {
            file_put_contents($this->file, '0');
        }
    }
    public function add_view() {
        $prev_count = file_get_contents($this->file);
        file_put_contents($this->file, $prev_count+1);
    }
    public function get_view() {
        $count = file_get_contents($this->file);
        return $count;
    }
}
$view = new pageView;

//add one another pageview
$view->add_view();

//Echo total pageviews
echo 'Total Pageview: '.$view->get_view();
?>

First of all it will check the file decleared on $file variable this is done with PHP's __construct function. When you call add_view function will add one more number to existing pageview. If you call get_view function this will return total pageview.

Cheers!!! Congratulation mate, you just learned to create simple hit counter in PHP. Hope to see you in comment section below...

Comments (0) Add New Comment
No comments, Be first one to commment!