views:

215

answers:

6

How can I detect the site the user came from before accessing mine in PHP?

+4  A: 

Try this:

$_SERVER['HTTP_REFERER']

For more information, please see HTTP referrer:

The referrer, or HTTP referrer—also known by the common misspelling referer that occurs as an HTTP header field—identifies, from the point of view of an internet webpage or resource, the address of the webpage (commonly the URL, the more generic URI or the i18n updated IRI) of the resource that links to it. By checking the referrer, the new page can see where the request came from.

Andrew Hare
A: 

You need to look at the HTTP Referer Header:

$_SERVER['HTTP_REFERER']

See PHP Documentation for more HTTP Headers

Dancrumb
+13  A: 

You could check at the Referer HTTP Header :

echo $_SERVER['HTTP_REFERER'];


But note that the Referer is sent by the browser, which means :

  • It can be disabled (it's not mandatory, and is just an additionnal information that the browser can send)
  • It can be faked (i.e. anyone can send anything -- even some SQL injection, or XSS injection, for instance)


So, you can use the referer to provide an additional feature on your website, but you have to make sure that your website doesn't rely on it : your application must still work, even if the Referer is not present.

Pascal MARTIN
+1 Good points about disabling and spoofing.
Andrew Hare
@Andrew : as a end-user, I hate when I'm on a website and something doesn't work just because the referer is disabled in my browser *(which sometimes happens, as I often disable it to test some stuff ; sometimes in the websites I develop)*
Pascal MARTIN
+2  A: 
echo $_SERVER['HTTP_REFERER'];

It's not entirely reliable and can be spoofed, but in general it will be populated with the URL that the user clicked to get to the script.

sidereal
A: 

The above notes are correct, but keep in mind that the user can make his/her browser not send this information, or they can mess with this information and send false data.

Doron
+1  A: 

As @Andrew Hare states in his answer, getting the value of the HTTP_REFERRER server value (which is a header that is sent as part of the HTTP request) will tell you the site that the browser was last on.

What should be noted, however, is that it is completely possible that this header/server variable will have no value, for a number of legitimate reasons, some being:

  • The user typed in the URL to the site in the same window
  • The user opened a bookmark in the same window
  • The user just opened the browser and did one of the things above

All of the above are really variations on the same thing, a case where the same browser window is used for going to another site, but wasn't prompted through clicking the on a link in a document which lead them there, a redirect, or some other action prompted by the page in the history before yours.

casperOne