I've just created a function to check if your IP is within an array of IPs. The IP array can contain ranges like 192.168/170.50.0/255. I have a working example, but it seems a bit clunky to me.
Is there anything wrong with my method, or anything I could improve?
<?php
function checkIpWhitelist($whitelist, $yIp){
$ips = $whitelist;
$ySplitIp = explode('.', $yIp);
$found = null;
// Loop each IP.
foreach($ips as $ip){
// Explode it into parts.
$splitIp = explode('.', $ip);
// Each part.
foreach($splitIp as $index => $part){
// If this IP has failed a part, skip the rest of it.
if($found === false){
continue;
}
// Default to an array of just the part value.
$range = array($part);
// If the part contains a /, it's a range.
if(strpos($part, '/') !== false){
// Split the range.
$range = explode('/', $part);
// Make a new array, containing the full range.
$range = range($range[0], $range[1]);
}
// If the part is in the range.
if(in_array($ySplitIp[$index], $range)){
$found = true;
} else {
$found = false;
}
}
// If $found is true, all IP sections are matched. If not, reset $found to null.
if($found === true){
return true;
} else {
$found = null;
}
}
return $found;
}
$yIp = '192.168.59.3';
$whitelist = array(
array(
'192.168.60.1',
'192.168.0/50.3',
'192.160/170.59.4'
),
array(
'192.168.60.1',
'192.168.0/50.3',
'192.160/170.59.3',
'192.168.59.3'
),
array(
'192.168.60.1',
'192.168.0/50.3',
'192.160/167.59.3',
'190/193.160/169.50/60.0/5',
'192.168.59.3'
)
);
foreach($whitelist as $list){
var_dump("\n\n" . (checkIpWhitelist($list, $yIp) ? 'IP in range!' : 'IP not in range') . "\n\n");
}
?>
The examples return:
IP not in range
IP in range!
IP in range!