开发者

Checking PHP referrer

开发者 https://www.devze.com 2023-02-11 12:17 出处:网络
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.

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 th开发者_运维技巧e regex needs to match the FIRST occurance found.


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
}


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


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


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.


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消