Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking PHP referrer

Tags:

regex

php

So, I need to check the referrer to a page using php, and if it is *.example.com, or *.anothersite.com, execute code, but if not, redirect elsewhere.

How would I go about checking if the HTTP_REFERER is equal to those values, with a wildcard character?

Thanks!

EDIT: The url will contain more than one domain, so the regex needs to match the FIRST occurance found.

like image 920
Jake Lee Avatar asked Feb 17 '11 18:02

Jake Lee


5 Answers

Should do it:

$allowed_host = 'example.com';
$host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);

if(substr($host, 0 - strlen($allowed_host)) == $allowed_host) {
  // some code
} else {
  // redirection
}
like image 162
seriousdev Avatar answered Oct 17 '22 15:10

seriousdev


Other answers' checks' are good but are not strictly bound to your website. So for example referer with value http://attacker.com/www.example.com/ will pass almost all the checks. And it is very easy to make such site and just send a cross-domain request.

There is a reliable and secure method to check if referer is really your domain. Of course referer can be spoofed, but a victim of an attacker site will send correct referer.

The trick is in ^ special character. Here is the magic regex:

^https?://(([a-z0-9-]+)\.)*example\.com/

^ - ensures that we are at the start
https? - protocol - http or https
(([a-z0-9-]+)\.)* - matches subdomains, also of higher levels, if any
example\.com - matches main domain
/ - ensures start of path so domain name cannot continue

like image 33
Zaffy Avatar answered Oct 17 '22 15:10

Zaffy


$ref = $_SERVER['HTTP_REFERER'];
if (strpos($ref, 'example.com') !== FALSE) {
   redirect to wherever example.com people should go
}
if (strpos($ref, 'example.org') !== FALSE) {
    redirect to wherever example.org people should go
}

Of course, this only works if the referer is "nice". For instance, coming from google you could possibly have "example.org" in the search term somewhere, in which case strpos would see it, and redirect, even though you came from google.

like image 36
Marc B Avatar answered Oct 17 '22 14:10

Marc B


preg_match('/(.+?)\.example\.(com|org)/',$_SERVER['HTTP_REFERER'])

This will only match an address that has a subdomain, and it also will not continue looking for anything beyond subdomain.example.com or .org. i.e. subdomain.example.com/some-other-stuff. Do you need to also match either of these?

Correction - this will match www.example.com but will not match example.com.

like image 1
Sean Walsh Avatar answered Oct 17 '22 14:10

Sean Walsh


Try this:

if (preg_match('/\.example\.(com|org)/', $_SERVER['HTTP_REFERER']))
{
  // execute your code
}
else
{
  header("Location: http://example.com/redirectpage.htm");
  exit();
}
like image 1
Michael Berkowski Avatar answered Oct 17 '22 15:10

Michael Berkowski