PHP program to store page views count in SESSION, to increment the count on each refresh, and to show the count on web page.
Session: A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable which is associated with that session.
The concept of session is more visible and practical when we explain building log in form using MySQL database. Until then, memorize the above definition!
In this PHP program, as the above question suggests: we are storing the page view count in a session variable and incrementing it on each page view.
Mechanism used:
On the first visit, the session variable is set to 1 and as this is the first visit, a message “Session does not exist” is displayed on the web page.
As the session variable is set to 1 on first visit, on consecutive visits the code inside the if block is executed and the value of the session variable is echo’ed or printed on to the browser and then incremented by one.
Video Tutorial: Store Page View Count In Session Variable: PHP
[youtube https://www.youtube.com/watch?v=VmB6ZrhLAp0]
Source Code: Store Page View Count In Session Variable: PHP
(session.php)
<?php session_start(); if(isset($_SESSION['count'])) { echo "Your session count: ".$_SESSION['count']."<br />"; $_SESSION['count']++; } else { $_SESSION['count'] = 1; echo "Session does not exist"; } ?>
Code Explanation: Logic
session_start() is a standard call and is mandatory step to start the session. On each page, wherever you use the session variable, you must write session_start() before using the session variable. It is a usual practice to write session_start(); as the first line of code in a php program whenever necessary.
$_SESSION[‘sessionName’] is a session variable. sessionName is the session name and it should be enclosed within single quote.
isset() is a standard php function which returns true or false depending upon whether the passed parameter is set or not.
In all major programming languages(including PHP) we use shorthand notations like $_SESSION[‘count’]++; which means $_SESSION[‘count’] = $_SESSION[‘count’] + 1; Here ++ is called increment operator.
And in $_SESSION[‘count’]- -; which is equal to writing $_SESSION[‘count’] = $_SESSION[‘count’] – 1; Here – – is called decrement operator.