gio
gio

Reputation: 975

is $_SERVER['HTTP_REFERER'] safe?

I'm using $_SERVER['HTTP_REFERER'] to generate a dynamic back link.

<a href="<?php echo $_SERVER['HTTP_REFERER'] ?>">Return to..blah</a>

Is it reasonably safe to do so?

Upvotes: 15

Views: 17000

Answers (3)

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14941

It's not. It might not be set, unwanted or even unsafe.

Concider the following:

  1. User types in your url and hits go. There will not be an referrer. Not only will your back-button not work, you'll receive an notice error as well.
  2. The visitor comes from an external source (lets say google) on your product page. do you want to send your visitor back to google? I don't think so.
  3. The header can be modified, I'd go for either double checking it, or not using it at all.

Upvotes: 2

Piskvor left the building
Piskvor left the building

Reputation: 92752

It may be safe, but it is not reliable: due to the HTTP spec, HTTP_REFERER is optional (some clients don't send this header at all, and some "security" software strips this out from any HTTP request), and there are numerous ways to modify this header. Some browsers send the referring page, some send a blank string, some don't send this at all, some may send bogus data, some may send Aunt Matilda; and moreover, you can't tell whether you're getting valid data in this header or not.

So, no, I would never trust that HTTP_REFERER contains the previous page, and neither should you.

Upvotes: 6

Quentin
Quentin

Reputation: 943207

Not like that.

It might not be present. (It might be wrong, some personal firewall packages obfuscate the referer for privacy reasons, violating the HTTP spec along the way)

You should run anything coming from outside your system through htmlspecialchars to guard against XSS attacks (although, IIRC, the referer should never have any dangerous characters in it as they should be URL safe you should keep in the habit of always being cautious).

Browsers come with back buttons though, there is no need to try to duplicate their functionality (especially when, with this, if the user clicks a link marked "back" it doesn't take them back in their history, so clicking the normal back button will conceptually take them forwards).

Upvotes: 14

Related Questions