views:

165

answers:

4

Using PHP I'd like to compare an actual ip address to part of one, and see if it matches. For example I want to see if the address matches 12.34..

<?php
$rem_address = getenv('REMOTE_ADDR');
$temp = substr ($rem_address,0,6)
if ($temp == "12.34.") echo "It's a match";
?>

Is there an easier/better way to do this?

+2  A: 
matei
A: 
<?php
$full_address = getenv('REMOTE_ADDR');
$pattern = "/^" . preg_quote('12.34') . "/";
$count = preg_match($pattern, $full_address);
if ($count!=0) {
//match
}
?>
RadiantHeart
Why change `getenv('REMOTE_ADDR');` to `getenv['REMOTE_ADDR'];` Do the () do something different then the []?
aslum
My mistake, no reason to change it. In fact it would not work. Corrected.
RadiantHeart
+3  A: 

The function strpos($haystack, $needle) will tell you the first position in the $haystack string where the substring appears.

As long as you are careful to check the with the === comparison operator, you can see if "12.34" appears at the beginning of the IP address.

if (strpos ($rem_address, "12.34.") === 0) echo "It's a match";

Check out the documentation and pay careful attention to the Warning.

JSchaefer
Good solution, but I would add a dot after 34. ;-) Just to be sure of course... since IPv4 segments shouldn't exceed 255.
fireeyedboy
Excellent suggestion! I've fixed that. (I should have been more careful about copying the original test string.)
JSchaefer
Assuming (as is the case here, but might not always be) that the fragment you're matching is always going to be the same, you COULD do `FOO.BAR` as long as BAR is 26 or higher. If it's <=25 you might run into false positives when you match 12.244 with 12.24. On the other hand you'll never run into 12.345. Still probably safest to do 6 characters in case someone else is modifying the code later, or the IPs change.
aslum
A: 

Yet more methods, based on ip2long:

(ip2long($_SERVER['REMOTE_ADDR']) & 0xFFFF0000) == 0x0C220000
! ((ip2long($_SERVER['REMOTE_ADDR']) & 0xFFFF0000) ^ 0x0C220000)
! ((ip2long($_SERVER['REMOTE_ADDR']) ^ 0x0C220000) >> 16)
outis