PHP :: Using Session Variables to Store Browser Navigation History

Leave a Reply

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)
Loading...

This post is off-topic given the general theme of my blog, but I felt the content useful enough to be posted. I am developing a PHP/MySQL-based database and content management system to catalog my literally h-u-u-u-g-e classic stamps collection. That’s when I faced the problem of tracking browser history, did an awful amount of googling, and found nothing that could help me. I am not a professional web developer, I do it as a hobby. So forgive me for any unintentional errors.

The Problem:

The most popular way to track a user’s browsing history is to use the javascript history object, e.g. something like: javascript:history.go(-1). My problem was that I had multiple frames on the page, and javascript wouldn’t work the way I expected it to. So I was looking for a workaround, something that wouldn’t be client-side.


The Solution:

After searching for some time, I realized I could effectively create a MySQL table, associate it with a session, store browsing history, and delete the table using cron jobs, which checks for non-current sessions. That didn’t turn out to be very simple. Then I remembered PHP session variables! Session variables are associated with each session, and I could define custom session variables and arrays. Once the session has expired, the arrays would to. Just having a session variable as an array would do the trick!

So here’s the code, including explanatory comments. The first snippet is where all the functionality is, the second snippet is where I demonstrate use of the functions.

The code: history.php
(Include this at the top of all PHP files as in page_1.php below)

<?php

// Start a new Session
session_start();

// Get Current Page Address with Complete Path
$cur_add= "http://".$_SERVER['HTTP_HOST'] .$_SERVER['REQUEST_URI'];

// If 'Back' or 'Forward' link was not clicked to reach current page
// Then that page is valid to be entered into the history list
if (!isset($_GET['prev']) & !isset($_GET['next']))
{
    // If Session has not been initiated before
   if ($_SESSION==NULL)
   {
      // Set history count as 0
      $_SESSION['count']=0;

     // Store current page address in the history as 0th entry
      $_SESSION['pageadd'][$_SESSION['count']]=$cur_add;

   }

   // If Session has been initiated before
   else
   {
     // Increase counter pointing to current page
     $_SESSION['count']=$_SESSION['count']+1;

     // Store current page address in history list as count-th entry
     $_SESSION['pageadd'][$_SESSION['count']]=$cur_add;

     // If user went back in history and 
     // then branched off differently
     // this line ensures that the old history 
     // branch is discarded with preceding entries intact
     $_SESSION['pageadd']=
       array_slice($_SESSION['pageadd'],0,$_SESSION['count']+1);
   }
}

// If 'Back' link was clicked to reach current page
elseif (isset($_GET['prev']))

{
   // Decrease the counter pointing to an entry in history link list
   // Make no change to history entries
   $_SESSION['count']=$_SESSION['count']-1;

}

// If 'Forward' link was clicked to reach current page
elseif (isset($_GET['next']))

{
   // Increase the counter pointing to an entry in history list
   // Make no change to history entries
   $_SESSION['count']=$_SESSION['count']+1;

}

// If the function 'prev1' has not been declared before
if (!function_exists('prev1'))

{
   // This function generates the 'Back' link
   function prev1()
      {

          // If session has been initiated and current count 
          // points to anything but the first entry
          if (($_SESSION!=NULL) & $_SESSION['count']>=1)

          {
              // Generate the link to previous page in history, 
              // including a flag to make the page realize 
              // it doesn't have to go into the list as a new entry
              echo "<a href=".
                 $_SESSION['pageadd'][$_SESSION['count']-1].
                  "?prev=1>Back</a>";
              echo '<br>';
          }
      }
}

// If the function 'next1' has not been declared before
if (!function_exists('next1'))

{
   // This function generates the 'Forward' link
   function next1()

      {
          // If Session has been initiated and current count
          // points to anything but the last entry
          if (($_SESSION!=NULL) & 
               $_SESSION['count']<count($_SESSION['pageadd'])-1)

          {
               // Generate the 'Forward' link,
               // including a flag to make the next page 
               // realize it shouldn't go as a new entry in the list
               echo "<a href=".
                 $_SESSION['pageadd'][$_SESSION['count']+1].
                    "?next=1>Forward</a>";
               echo "<br>";
          }
      }
}

?>

page_1.php
(This is a typical content page that calls the above function)

<?php

// Include the history functionality
include_once('history.php');

// List of Links
echo "This is Page 1";
echo '<br>';
echo "<a href=page_2.php>Page 2</a>";
echo '<br>';
echo "<a href=page_3.php>Page 3</a>";
echo '<br>';
echo "<a href=page_4.php>Page 4</a>";
echo '<br>';
echo "<a href=page_5.php>Page 5</a>";
echo '<br>';
echo "<a href=page_6.php>Page 6</a>";
echo '<br>';
echo "<a href=page_7.php>Page 7</a>";
echo '<br>';
echo "<a href=page_8.php>Page 8</a>";
echo '<br>';

// Displaying the contents of history for checking
$ct = 0;
foreach($_SESSION['pageadd'] as $pageadd)
{
	$ct = $ct+1;
	echo 'Page History Entry #'.$ct.' of '.
            count($_SESSION['pageadd']).' is '.$pageadd.'<br>';
}
echo '<br>';

// Calling the functions to generate Back and Forward Links
prev1();
next1();

// Include a page to allow destroying the session 
// (for code check purpose)
echo "<a href=sess_test.php>Destroy Session</a>";
?>

Explanation & Usage:

The above codes are quite self-explanatory. All you have to do is copy the history.php file to your web root, and include it in any page you want to be tracked in history. The example is shown in page_1.php above, where history.php is included. Whenever the ‘Back’ and ‘Forward’ Links are to be included, just call the functions prev1() and next1().

Sample:

Click here to see a sample at work!

Download:

Download the zip archive for the above example here.

Leave a Reply

Leave a Reply