Skip to content

PHP program to find number of page views

A PHP program to store page view count in a SESSION variable and to increment the count on each web page refresh. This session variable is displayed on the web page which contains the number of page views count.

 

//ViewsCount.php

<?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.

//countReset.php

<?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 PHP Script?

  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.

1 thought on “PHP program to find number of page views”

Comments are closed.