PHP Program to count Page Views

What is a session?

A PHP session is used to store data on a server rather than the computer of the user.Session identifiers or SID is unique numbers which are used to identify every user in a session based environment.The SID is used to link the user with his information on the server like posts, emails etc. You can learn about sessions in details in the article PHP | Sessions

How to use sessions for Storing Page Counts



A session mechanism can be used to store page views which increment on each refresh and show the count on a webpage. A session is user specific and for every user, a separate session is created along with a separate session variable which is associated with that session.
Using this mechanism, for every user the session variable is set to 1 initially for the first visit.On consecutive visits, the value of this session variable is incremented and displayed on the output webpage.

Below is the PHP program to store page count:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
  
session_start();
   
if(isset($_SESSION['views']))
    $_SESSION['views'] = $_SESSION['views']+1;
else
    $_SESSION['views']=1;
      
echo"views = ".$_SESSION['views'];
  
?>

chevron_right


Output:

Explanation
Below is the explanation of above code:

  1. session_start() :It is a first step which is used to start the session. It is a standard call. The session_start() should be used whenever the session variable is used.
  2. $_SESSION[‘views’] :This is the session variable which is used to store views count for a user’s session. ‘views’ is the session name. The session name should be always be enclosed within the single quote.
  3. isset() : It is a standard php function which returns true or false depending upon whether the passed parameter is set or not.

We can also reset the session variable. Below program shows how to reset a session in PHP:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
session_start();
$views = $_SESSION['views']; 
   
unset($_SESSION['views']); 
session_destroy();
  
 ?>

chevron_right


Output:



My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.