2

This is what I'm using after every form to go back to the previous page in a multi-page form:

$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<a href='$url'>GO BACK</a>";

But I'm not sure if it will work fine. Is there any better method for going back to the previous page. I don't want to use header (location:), maybe multiple submit, i.e. one to submit the form and another for going. But I'm not sure how to implement it properly.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
Shady7447
  • 89
  • 11
  • 4
    Possible duplicate of [Back to previous page with header( "Location: " ); in PHP](http://stackoverflow.com/questions/5285031/back-to-previous-page-with-header-location-in-php) – S.I. Nov 15 '16 at 08:07

1 Answers1

2

As it is said in the documentation, not all user agents set referer:

'HTTP_REFERER'

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

In other words, $_SERVER['HTTP_REFERER'] may be empty.

I would rather use JavaScript:

<a href="javascript:history.go(-1)">Back</a>

Sometimes it is possible to determine the previous page by the logic of your application. For example, if a page "Step 2" goes after a page "Step 1", then I would generate a URL according to the logic: /registration/step1, /registration/step2, etc. This is the most reliable way.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
  • history.go() will be based on browser history right? if user is accessing more than 1 site at the same time ,then? – Shady7447 Nov 15 '16 at 09:04
  • 1
    @Shady7447, right. Then it will work as browser's "back" button. That's why you should generate links according to the logic of your app – Ruslan Osmanov Nov 15 '16 at 09:09