Jake Lee
Jake Lee

Reputation: 7979

Checking PHP referrer

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.

Upvotes: 7

Views: 38911

Answers (5)

Marc B
Marc B

Reputation: 360602

$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.

Upvotes: 5

user823738
user823738

Reputation: 17521

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

Upvotes: 7

seriousdev
seriousdev

Reputation: 7656

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
}

Upvotes: 31

Michael Berkowski
Michael Berkowski

Reputation: 270607

Try this:

if (preg_match('/\.example\.(com|org)/', $_SERVER['HTTP_REFERER']))
{
  // execute your code
}
else
{
  header("Location: http://example.com/redirectpage.htm");
  exit();
}

Upvotes: 1

Sean Walsh
Sean Walsh

Reputation: 8344

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.

Upvotes: 1

Related Questions