Back to Previous Page (PHP)

Your rating: None Average: 3.8 (56 votes)

While working on one of our projects we came across a requirement which was basically a Link which takes you to the previous page within the same site.

We googled and found a lot of ways which were complex. After giving it a thought, we just figured out that its a very simple logic with a few lines of code.

Well, our requirement was for a Drupal site so got the logic on PHP. Here it goes [sharing is our policy] :

<?php session_start(); ?> <!-- Starting a session before the DOCTYPE -->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

<a href="<?php echo $_SESSION['back']; ?>">back</a> <!--The anchor tag that links to the previous page -->

<?php $_SESSION[’back’] = htmlentities($_SERVER[’REQUEST_URI’]); ?>  <!-- Assigning the current URL to a session variable -->

Please note that first we assign the previous session variable to the anchor tag and only then re-assign the current URL to the session variable which will be read when you move on to the next page.

This being a simple PHP snippet can be used in almost every CMS (PHP based) and sure is a good addon to the accessibility of your site.

Trackback URL for this post: