PHP program to find number of page views

By | July 10, 2017

A PHP program to store page view count in SESSION, to increment the count on each  refresh, and to show the count on web page

 

<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo"views=".$_SESSION['views'];
?>
Output:
views = 1
Refresh the browser
views = 2

 

Suggested Read:

 

The following code can be used to reset the views count to 1.

<?php
session_start();
$views = $_SESSION['views']; //retrieve the session variable
unset($_SESSION['views']); //to remove session variable
session_destroy(); //destroy the session
?>

The output on the browser:

PHP program to find number of page views using session

shows the initial count

PHP program to find views count using session

Count after the first refresh

 

How to execute this program?

  1. You need to copy the file ViewsCount.php to a PHP server. You can use wampserver software which provides an integrated environment to run PHP files along with MySQL database support.
  2. Next, open this PHP file on the browser via localhost URL. Usually http://localhost/ViewsCount.php
  3. Initially, your browser will display the result  as views=1
  4. Refresh the web page to check the increase in page views.

Please let me know if you come across any issues.




Author: Ravi Bandakkanavar

A Techie, Blogger, Web Designer, Programmer by passion who aspires to learn new Technologies every day. It has been 6 years since I have been publishing articles and enjoying every bit of it. I want to share knowledge and build a great community with people like you.

Suggested articles for you:

Did it help? Comment here..