tags:

views:

490

answers:

6

Hi,

just a short question, is it save to create an back link with :

$backLink = htmlentities($_SERVER['HTTP_REFERER']);

or is there an better solution ?

+1  A: 

It's quite safe, as long as you check for its existance. In some browsers it can be turned off, and I'm not sure that it's mandatory for browsers anyhow. But the baseline is, you can't count on it existing. (RFC2616 doesn't say the referer-header must exist.)

If you really need reverse navigation, perhaps you could instead use a session variable to save the previous (current really, but only update it after displaying the back-link) page visited.

nikc
A: 

Given that:

  • The referer header is optional
  • Some security software will rewrite the referer header (e.g. to XXXX:XXXXXXXX or Advert For Product)
  • Linking to the referer will, at best, duplicate the built in functionality of the back button
  • User's will often expect a link marked 'back' to take them to the previous page in a sequence, not to the previous page they were on

No, it isn't safe. The dangers are not great, but the benefits are tiny.

David Dorward
A: 

It will work in some cases. However, you should be aware that the HTTP referer header is not guaranteed. User agents (browsers, search spoders etc) cannot be relied on to send anything, correct or not. In addition, if a user browses directly to the page, no referer header will be present. Some internet security software products even strip out the HTTP referer for "security" reasons.

If you wish to use this solution, be sure to have a fallback in place such as not showing the back link, or linking to a default start page or something (it would depend on the situation this is to be used in).

An alternative solution might be to use javascript to navigate to "history.back". This will use the browser's back/history function to return to the previous page the user was on.

Splash
+2  A: 

An easier way might be to do something like this:

<a href="javascript:history.back()">Go back</a>

That does not rely on the browser populating the Referer header, but instead does exactly the same thing as pressing the browser "Back" button.

This may be considered better since it actually goes back in the browser history, instead of adding the previous page to the browser history in the forward direction. It acts just as you would expect the Back button to act.

Greg Hewgill
Note, though, that you should only add this link using javascript in the first place, since otherwise the link won't do anything other than frustrate Joe Surfer.
nikc
That's true. Graceful degradation is recommended.
Greg Hewgill
A: 

I think Facebook use a similar technique to redirect the user.

They use GET variable called 'from'.

Boris Guéry
A: 
FractalizeR