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

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

//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 (1) Add New Comment
sklep online2024-02-23 7:15 AM

Wow, marvelous weblog format! How lengthy have you been blogging for? you made running a blog glance easy. The whole look of your web site is great, let alone the content! You can see similar: e-commerce and here dobry sklep