I'm using preg_match to match a referring url AND and an IP block. How do I tell my code to look for the referral, then if it matchs check multiple IP blocks? ie: 70.x.x.x OR 96.x.x.x
Here is my code so far (that works with one IP block "70.x.x.x")
<?php
$referrer = $_SERVER['HTTP_REFERER'];
$visitor = $_SERVER['REMOTE_ADDR'];
if ((preg_match("/referrer-domain.com/",$referrer)) && (!preg_match("/70./",$visitor))){
echo "<meta http-equiv='refresh' content='0;url=http://www.new-domain.com'>";
}
?>
I know this is a simple question, just having a brain fart today.
preg_match("/(70|96)./",$visitor)
It should also probably be:
preg_match("/^(70|96)\./",$visitor)
or you'll be blocking 1.2.96.4 and 1.2.3.70 etc. as well.
You can achieve this using regular expressions' "alternation" syntax, which is basically an OR operator. You will also need to anchor the expression to the beginning of string using "^", which will ensure that you're matching against the first octet of the IP, and a backslash to escape the dot, which is a wildcard in regular expressions.
This snippet should work for you:
<?php
$referrer = $_SERVER['HTTP_REFERER'];
$visitor = $_SERVER['REMOTE_ADDR'];
if ((preg_match("/referrer-domain.com/",$referrer)) && (!preg_match("/^(?:70|96)\./",$visitor))){
echo "<meta http-equiv='refresh' content='0;url=http://www.new-domain.com'>";
}
?>
You may also want to consider just using PHP's header() function instead of a meta refresh, i.e.:
if ((preg_match("/referrer-domain.com/",$referrer)) && (!preg_match("/^(?:70|96)\./",$visitor))){
header("Location: http://www.new-domain.com");
}
An alternate and arguably better, solution is to use the php's ip2long() function.
That turns a dotted IP address into an integer, and you can do your comparisons using > and < logic.
eg.
ipstart = sprintf("%u", ip2long('70.0.0.0'));
ipend = sprintf("%u", ip2long('70.255.255.255'));
$visitor = sprintf("%u", ip2long($visitor = $_SERVER['REMOTE_ADDR']));
$referrer = sprintf("%u", ip2long($visitor = $_SERVER['HTTP_REFERER']));
if (($visitor < $ipstart | $visitor < $ipend) | ($referer < $ipstart | $referer < $ipend) ){
header('location: http://www.new-domain.com');
}
If $ipstart and $ipend were arrays of valid IP ranges you could iterate over them to check any number of different IP ranges.
Check out http://php.net/manual/en/function.ip2long.php for why the use of sprintf is important, and for some other things to watch out for with partial IP addresses, etc.