What's wrong with this $_SERVER['HTTP_REFERER'] code?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

What's wrong with this $_SERVER['HTTP_REFERER'] code?

Post by simonmlewis »

Code: Select all

if (strstr($_SERVER['HTTP_REFERER'], 'http://www.site.com/cart.asp') !== false) 
{
    echo "<div class='downarrowdiv' id='addtobasket'>
Added to Basket
</div>";
}
I'm being told:
[text]Notice: Undefined index: HTTP_REFERER in C:\xampp\phpMyAdmin\site\index.php on line 233[/text]
I've not had this before. It's meant to find out where the page has come from, and then show the Div on screen fora short time.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: What's wrong with this $_SERVER['HTTP_REFERER'] code?

Post by Celauran »

Same as every other undefined index notice; you're not checking if $_SERVER['HTTP_REFERER'] is set before trying to use it. Sometimes it's not, so you get that notice.
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: What's wrong with this $_SERVER['HTTP_REFERER'] code?

Post by twinedev »

you need to also check to see if 'HTTP_REFERER' actually exists, there are some times when it doesn't exist. (Also side note, if it does exist, this is one of those items you cannot trust as it is supplied by the visitor of the site, so treat it like you would something passed via $_POST/$_GET)

Also note, that some people block (either on purpose or some typ eof AV software) the browser from sending the referrer.

for your code:

Code: Select all

if ( isset($_SERVER['HTTP_REFERER']) && strstr($_SERVER['HTTP_REFERER'], 'http://www.site.com/cart.asp') !== false) 
Post Reply