Hello.

The task is to save the referrer to cookies. I use this code:

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

If during the life of a session you arrive at the target page from different sources, then the very first source is saved in the cookie and is not overwritten every time (which is necessary).

The problem is that the cookie is overwritten every time you wander through the site’s own pages (the top code is shown on each page), despite the condition for the existence of a cookie named " last_ref ". If, however, prohibit memorizing the referrer, which coincides with its own site, then the cookie is generally empty.

What is wrong in the code?

    2 answers 2

    The question of what is meant by different sources. If these are transitions from other sites, then we need a check for this, respectively.

     $MySite = "http://" . $_SERVER["HTTP_HOST"]; if (!empty($_SERVER["HTTP_REFERER"]) and substr($_SERVER["HTTP_REFERER"],0,strlen($MySite)) != $MySite) { # Проверяем куки и если нужно устанавливаем } 

    Just browser each time exposes Referer: when it follows links (no matter which site of its own or someone else’s)

      Without thinking too hard, you can suggest creating a flag in $ _SESSION that indicates that the referrer has been set. Thus, during the existence 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; } 

      perhaps you can remove the $ _COOKIE ['last_ref'] existence check