Search code examples
phphtmlwordpresssessionhttp-referer

How do I prevent HTTP_REFERER from being overwritten


Before the <html> tag in the header.php file of my WordPress site I have the following code:

<?php

session_start();

$_SESSION['refererurl'] = $_SERVER['HTTP_REFERER'];

?>

To test the above code, I placed the following code in the front-page.php file (and it works):

<?php
    echo $_SESSION['refererurl'];
?>

I'm doing this because I want to track the referrer URL that led a visitor to my site from an external site (for goal tracking purposes). The problem is that $_SERVER['HTTP_REFERER'] resets on page-load, so while the information is useful when a visitor first lands on my website, it's overwritten whenever the visitor navigates further into my site.

Is there any way to store the value of $_SERVER['HTTP_REFERER'] when a visitor first arrives at my site from an external site for as long as the visitor is on my site?

I'm rather new to PHP at this level, so please excuse my lack of experience. I'm storing $_SERVER['HTTP_REFERER'] in a session simply because that's what I've gathered would work based on some quick research into sessions and cookies.


Solution

  • Very simple - only set it if it isn't already set.

    if(!isset($_SESSION['refererurl'])) {
        $_SESSION['refererurl'] = $_SERVER['HTTP_REFERER'];
    }