Page referrer?

I’m trying to figure out where the user came from anddd am using

$referrer = substr(basename($_SERVER['HTTP_REFERER']), 0, strpos(basename($_SERVER['HTTP_REFERER']), "?")); 

It seems to work when I

echo $referrer;

As I get
but when I view the source, I see

<b>Notice</b>:  Undefined index: HTTP_REFERER in <b>C:\Users\lurtnowski\webserver\htdocs\DCT\2\furniture\position_furniture.php</b> on line <b>8</b>

What gives? Aren’t I using the function poroperly?

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.

Try the following and note the differences between direct calls and referring pages:

<?php declare(strict_types=1);
ini_set('display_errors', '1');

echo '<pre>'; // adds linefeeds for easier reading
print_r( $_SERVER );
echo '</pre>';


Corrected syntax errors

As igor_g says, HTTP_REFERER can’t really be trusted and won’t always be set (eg. if the user arrives directly at the page) but if you want to use it it’s best to check if it’s set first. The ‘Undefined index’ notice you quote is because it’s not set, so use something like this:

if (isset($_SERVER['HTTP_REFERER'])) {
 $referrer = substr(basename($_SERVER['HTTP_REFERER']), 0, strpos(basename($_SERVER['HTTP_REFERER']), "?"));
} else {
 $referrer = false;

As for why you’re seeing the Notice in the page source but not the page, perhaps the browser is re-requesting a fresh copy of the page when you view the source.

1 Like