Php If/Else Based Upon Http_Referer (else only showing blank)

903 Views Asked by At

Ok, so I'm trying to do a simple action where if a user was already viewing our site, we'll display a certain message, otherwise, we want to show a message for first time visitors (or just those without our URL as their referrer)

Else statement only shows as blank regardless how I seem to spin this.

Ideas?

<?php 
if (isset($_SERVER['HTTP_REFERER'])) {
    $referer = $_SERVER['HTTP_REFERER'];
    if (strpos($referer, "http://www.example.com/") === 0) {
        echo "Match Okay";
    } else {
        echo "No Match";
    }
}
?>
2

There are 2 best solutions below

0
On
1
On

Your code seem ok.

Quoted from the php docs:

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

Maybe your browser belongs to the category "Not all user agents will set this". Try your code with another browser.

For a more reliable way do to that, consider using cookies! Simply check for a cookie value. If it is not present, it's a first time visit (then set the value). If it is present, then it's at least the second page loaded.

The advantage of cookies is that you can track user if they come back again (by setting a persistence time for the cookie)