Forum Moderators: coopster

Message Too Old, No Replies

PHP Notice: Undefined index: HTTP REFERER

         

smallcompany

12:40 am on Feb 12, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hi,

I have a script that grabs the page where a certain action happens. If the http_referer is empty, I get the notice in my log file: PHP Notice: Undefined index: HTTP_REFERER for the first line of the code below.

$urlpx=parse_url(strtok($_SERVER["HTTP_REFERER"],'?'), PHP_URL_PATH);

if(empty($urlpx)) {
$urlp="NOREF";
}
else {
$urlp=$urlpx;
}


The rest after the first line is what I added in my attempt to make referer stop being undefined, but I still get the notices. I realized that the IF statement works fine, but notice is still there as there are no referers in some instances.

So, is it possible to prevent logging it from within the script? Something that would be added to the first line of the code?

Please note that I do want all logging to be ON as it is now.

Thank you

Peter_S

11:16 am on Feb 16, 2018 (gmt 0)

5+ Year Member Top Contributors Of The Month



Hi,

If your goal is to get ride of the "notice" you can do this :


if(isset($_SERVER["HTTP_REFERER"]))
{
$urlpx=parse_url(strtok($_SERVER["HTTP_REFERER"],'?'), PHP_URL_PATH);
}
else
{
$urlpx='';
}

smallcompany

4:45 am on Feb 17, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



For the time being, this seems to work right. Thanks very much!

Peter_S

12:23 pm on Feb 19, 2018 (gmt 0)

5+ Year Member Top Contributors Of The Month



You are welcome

robzilla

5:22 pm on Feb 19, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



To clarify, it's because you're trying to parse the variable without first checking if it even exists. When it doesn't, the function you call it on doesn't have any input. So regardless of what you do afterwards, the notice will still be given for line 1. That's why the code given by Peter_S does not throw a notice: it first checks if HTTP_REFERER is set and only parses it if that is true.

Peter_S

6:32 pm on Feb 19, 2018 (gmt 0)

5+ Year Member Top Contributors Of The Month



Just for the anecdote, in PHP 7+ there is the "Null Coalescing Operator" too :


$referer = $_SERVER["HTTP_REFERER"] ? ? "" ;


(without space between the two question marks, but for some reason the forum is not accepting two consecutive question marks).

The variable $referer takes the value of $_SERVER["HTTP_REFERER"] if it exists, otherwise takes an empty string (or something else)

robzilla

9:58 pm on Feb 19, 2018 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Nice, I'm sure that will come in handy sometime! Thanks for the tip.