aslum
aslum

Reputation: 12254

comparing actual IP with partial IP in PHP

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?

Upvotes: 0

Views: 2665

Answers (4)

RadiantHeart
RadiantHeart

Reputation: 266

<?php
$full_address = getenv('REMOTE_ADDR');
$pattern = "/^" . preg_quote('12.34') . "/";
$count = preg_match($pattern, $full_address);
if ($count!=0) {
//match
}
?>

Upvotes: 0

JSchaefer
JSchaefer

Reputation: 7291

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.

Upvotes: 4

outis
outis

Reputation: 77400

Yet more methods, based on ip2long:

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

Upvotes: 0

matei
matei

Reputation: 8685

$parts = explode(".",$rem_address);
if ($parts[0] == "12" && $parts[1] == "34") echo "match";

Upvotes: 2

Related Questions