I have a php script which sets the http referer to prevent (if not limit) its use by spammers. The part of the code that deals with this is as follows:

#----------
# Filter by Referer

function referer_check()
{

 $allowedreferers[] = 'http://mydomain.com/checkout.html';
 $allowedreferers[] = 'http://www.mydomain.com/checkout.html';

 $notfound = true;
 foreach ($allowedreferers as $referer_key => $referer_value) {
  if ($referer_value == $_SERVER['HTTP_REFERER']) {
   $notfound = false;
   break;
  }
 }

 if ($notfound === true) {
  header('Location: forbidden.html');
  exit;
 }
}

function DoStripSlashes($FieldValue) 
{ 
 if ( get_magic_quotes_gpc() ) { 
  if (is_array($FieldValue) ) { 
   return array_map('DoStripSlashes', $FieldValue); 
  } else { 
   return stripslashes($FieldValue); 
  } 
 } else { 
  return $FieldValue; 
 } 
}

#----------

My php script is emailing the contents of a javascript generated shopping cart. I cannot simply put http://www.mydomain/checkout.html as the http referer because the shopping cart script generates the checkout page with different suffuces all the time, eg: http://www.mydomain.co.uk/checkout.html?x=32&y=9

The shopping cart script is nopcart, so not my own creation and I have no idea how the suffix is generated or what it means. I just know that it is always different and so I am having trouble setting the http referer.

Something that would allow me to specify http://www.mydomain.co.uk/chechout.html and then some sort of wild card would be good.

Any suggestions?

    $regex = '#^http://(www\.)?mydomain.com/checkout.html#';
    if(!preg_match($regex, $_SERVER['HTTP_REFERER']))
    {
       header('Location: forbidden.html');
       exit;
    }
    

    Note however that the referer header is optional (and also easily spoofed), and you cannot necessarily be sure a user is not coming from an allowed referer just because it's not set in $_SERVER['HTTP_REFERER'].

      Thanks - that works a treat.

      I know that http referer isn't fullproof, I just like to add it as an extra layer of security.

        2 years later

        How can I edit this so that the domain can be either .com or .co.uk?

          Write a Reply...