I read, both on SO and other sites, that $_SERVER['HTTP_REFERER']
is something we, as programmers, should always avoid. Reading the PHP manual we encounter these lines:
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.
Considering "user agents" things such as Web Browser (Safari, Chrome, Opera, Firefox, basically they are all), the manual tell us that this variable may be changed by them. Here it comes my first question:
Question 1: Why should "users agent" modify this parameter? What are the reason for a web browser not to set this parameter?
It's just inquisitiveness, and i'll not use $_SERVER['HTTP_REFERER']
.
From my latest statement, it's oblivious that, if we do need of such a function, we need to figure something out. The first thing that comes in my mind is a cookie solution, in which we do something like:
setcookie('latest_page', __FILE__, 60 * 60 * 24 * 7);
And then, based on how you prefer to do it, you can recover what you need. Here it comes the second and last question:
Question 2: Is this way the best? Are there any way to improve it?
There is no reason to avoid
HTTP_REFERER
. Just when using it, be aware that it's not always set, and that it can be freely manipulated by the client, so it is untrusted data.The vast majority of clients sets the variable, and does so correctly.
The main reason for blocking it is privacy: For example, when opening an E-Mail in a web mail client, links to external images would carry the web mail service's address in the
HTTP_REFERER
header. That's why GMail and Yahoo make efforts to block it.The workaround you suggest works only for movements within the same site, and will break if the user has more than one tab/browser window open with which they browse your site. If you need to know the referring page, the superior method is to add a GET parameter like
Edit: One example where relying on HTTP_REFERER is dangerous would be showing a live-updated list of referring sites on your main page ("Visitors came from...") it would be easy to smuggle arbitrary URLs into that list by visiting your site with a fake
HTTP_REFERER
set.