简体   繁体   中英

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.

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

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

You can check if $_SESSION['refererurl'] is already set and simply don't override it :-)

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

You might also want to check if the referer is empty before trying to assign it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM