Alex
Alex

Reputation: 147

How to compare a variable to first part of HTTP_REFERER?

Please tell me, if I got a variable $var which returns: http://foo.com - then how can I check whether this uri is identical to what $referrer returns (given there is one), or to it's first part if $referrer = http://foo.com/oof/ or longer..?

With (any better way?):

$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

Basically I'd like to have an if/else case, for when the uri matches and when it doesn't. I'm also wondering how to it make hack-safe if you will, so that it can't be cheated when $referrer is fake like such: http://badsite.com/file.php?param1=http://foo.com, and so that here the http://foo.com part won't be considered a legit match.

Thanks a bunch!

Upvotes: 1

Views: 1016

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Quite literally:

if( substr($referrer, 0, strlen($var)) == $var)

"If the substring from the start of the referrer of the same length as the search term, is equal to the search term..."

In some cases, referrers may not be sent in the lowercase you might expect. To allow for this case, consider trying:

if( strcasecmp( substr($referrer, 0, strlen($var)), $var) == 0)

This performs a case-insensitive comparison on the start of the referrer vs. the search term.

Upvotes: 2

Abkarino
Abkarino

Reputation: 1446

To check the domain only:

$yoursite = ""; //Your site url without http:// or www.
$yoursite2 = ""; //Type your domain with www. this time

$referer = $_SERVER['HTTP_REFERER'];
$domain = parse_url($referer); 

if($domain['host'] == $yoursite || $domain['host'] == $yoursite2) {
     //Run your code here normally
}

Upvotes: 2

Related Questions