Save referer in cookies


The challenge is to store the referrer in a cookie. I use this code:

if( isset( $_SERVER['HTTP_REFERER']) && (!$_COOKIE['last_ref'])) { 
    SetCookie( 'last_ref', $_SERVER['HTTP_REFERER']); 

If you come to the landing page from different sources during the lifetime of the session, then the very first source is stored in the cookie and is not overwritten every time (which is what you need).

The problem is that the cookie is overwritten every time you browse your own pages of the site (each page has the top code), despite the existence of a cookie named “last_ref“. If you forbid remembering the referrer that matches your own site, then the cookie is generally empty.

What’s wrong with the code?

Answer 1, authority 100%

The question is what is meant by different sources. If these are transitions from other sites, then you need to check for this accordingly.

$MySite = "http://" . $_SERVER["HTTP_HOST"];
if (!empty($_SERVER["HTTP_REFERER"]) and substr($_SERVER["HTTP_REFERER"],0,strlen($MySite)) != $MySite) {

It’s just that the browser sets the Referer every time: when following links (no matter what site you own or someone else’s)

Answer 2, authority 50%

Without thinking too much, we can suggest creating a flag in $_SESSION to indicate that the referrer has been set. Thus, during the lifetime of the session, the referrer will not change… Something like

if( isset( $_SERVER['HTTP_REFERER']) && (!$_COOKIE['last_ref']) && ! isset($_SESSION['referer_saved'])) 
 SetCookie( 'last_ref', $_SERVER['HTTP_REFERER']);
 $_SESSION['referer_saved'] = true;

maybe we can remove the $_COOKIE[‘last_ref’] existence check