PHP $_SERVER['HTTP_REFERER'] vs. Javascript document.referrer?

4.1k views Asked by At

Ultimately I need to know what domain is hosting one of my javascript files. I have have read and experienced first hand that $_SERVER['HTTP_REFERER'] unreliable. One of the first 3 browser/computer combos I tested didn't send the HTTP_REFERER, and I know that it can be spoofed. I implemented a different solution using two javascript methods.

document.referrer

AND

window.location.href

I use the former to get the url of the window where someone clicked on one of my links. I use the former to see which domain my javascript file is included in. I have tested it a little so far and it is grabbing the urls from the browser very well with no hiccups. My question is, are the two javascript methods reliable? Will they return the url from the browser everytime or are there caveats like using the $_SERVER['HTTP_REFERER'] that I haven't run into yet?

1

There are 1 answers

3
A. Andres On

You should always assume that any information about the referrer URI is going to be unavailable (or perhaps even unreliable), due to browsers or users wanting to conceal this information because of privacy issues.

In general, you won't have the referrer information when linking from an HTTPS to an HTTP domain. Check this question for more info on this:

https://webmasters.stackexchange.com/questions/47405/how-can-i-pass-referrer-header-from-my-https-domain-to-http-domains

About using window.location.href, I'd say it's reliable in practice, but only because it's interesting that the client will supply the correct information so that applications depending on that will behave as expected.

Just keep in mind that this is still the client side sending you some information, so it'll always be up to the browser to send you something that is correct. You can't have control over that, just trust that it's going to work according to what is specified in the standard. The client might still decide to conceal it or fake it for any reason.

For example it might be possible that in some situations, like third party included scripts (also privacy reasons), the browser might opt to just leave it blank.