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.
$_SESSION['views'] = $_SESSION['views']+1;
echo"views = ".$_SESSION['views'];
views = 1
Refresh the browser
views = 2
The following code can be used to reset the views count to 1.
$views = $_SESSION['views']; //retrieve the session variable
unset($_SESSION['views']); //to remove session variable
session_destroy(); //destroy the session
The output on the browser:
How to execute this PHP Script?
- 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.
- Next, open this PHP file on the browser via localhost URL. Usually http://localhost/ViewsCount.php
- Initially, your browser will display the result as views=1
- Refresh the web page to check the increase in page views.
Please let me know if you come across any issues.