PHP: Simple $_SESSION Hit Counter Tutorial

This tutorial will cover 2 important aspects of learning PHP; 1) How to handle $_SESSION data, and 2) Increasing a variable by 1 using ++.

The example we are going to use today deals with a PHP page hit counter that will print out how many times a specific page has been viewed by the user. First, if you have no experience or need a refresher on how to declare and handle $_SESSION data, you will want to read that tutorial first.

<?php session_start(); ?>

Nothing fancy in the above code, all we are doing is declaring our session, but if you want to do it the right way, check to see if a $_SESSION exists first, and if it does not, then declare it, otherwise leave it alone.

<?php 
if(!isset($_SESSION)) { 
  session_start(); 
}
?>

All we are doing here is telling the page that if there has not been a $_SESSION set (isset), then to please start it. Now, lets get into the counter part of the tutorial.

<?php 
if(!isset($_SESSION)) { 
  session_start(); 
   $hits = 0;
    $_SESSION['views'] = $hits;
}
?>

Alright, here we have setup that if there is no $_SESSION set, then to start it, and after that, create a new variable called $hits, set that to 0 and then set our $_SESSION[‘views’] variable equal to $hits. The last part is to count up each time the page is loaded.

<?php 
if(!isset($_SESSION)) { 
  session_start(); 
   $hits = 0;
    $_SESSION['views'] = $hits;
} else {
   $hits++;
    echo "Page Views: " . $hits;
}
?>

There we are! The significant portion of this code deals with $hits++, which means to increment the $hits variable by 1 on each page load. That is all there is to it. You can now go off and program your own counter script, although hopefully it is a bit more advanced.

Leave a Comment

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