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'
?
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With