Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: What's the best way to check equality of $_SERVER['HTTP_REFERER']?

Tags:

security

php

I have a PHP script that checks the HTTP Referer.

if ($_SERVER['HTTP_REFERER'] == 'http://www.example.com/') {...}

However, this seems inherintly unsafe ... because what happens if the user goes to 'http://example.com/' or 'http://www.ExaMple.com' (both of which don't match the equality test).

Question: what's a better equality test to ensure that the HTTP Referer is coming from 'example.com' ?

like image 916
Hank Avatar asked Apr 05 '10 19:04

Hank


2 Answers

parse_url() combined with a bit of string juggling should do what you want. Try this:

$url = parse_url($_SERVER['HTTP_REFERER']);
//take the last two 'dot segments' of the host
$hostOnly = implode('.',array_slice(explode('.',$url['host']),-2));
if (strtolower($hostOnly) == 'example.com') {
    //stuff
}

Note that parse_url() can fail on badly formed URLs, so you might want to add some error checking to be safe. HTTP_REFERER could easily be filled with junk.

like image 190
zombat Avatar answered Sep 21 '22 02:09

zombat


Obligatory response: HTTP_REFERER can be spoofed so there is no way to be 100% sure anyone came from a specific website.

However if you do want to rely on it you can use a regex to look for "example.com" in the HTTP_REFERER. stristr() would also work, and probably would be recommended since it would be faster then a regex. It's also case insensitive so it would match "ExaMple.com" as well as 'example.com".

like image 39
John Conde Avatar answered Sep 23 '22 02:09

John Conde