Skip to content

Instantly share code, notes, and snippets.

@i-tabu
Last active June 27, 2016 05:19
Show Gist options
  • Save i-tabu/9ef3a15e4c1259843a64039bf4fb10d1 to your computer and use it in GitHub Desktop.
Save i-tabu/9ef3a15e4c1259843a64039bf4fb10d1 to your computer and use it in GitHub Desktop.
With the help of this static class, one can authenticate ip by providing, one or more allowed ips, ip pattern or ip CIDR.
<?php
/**
Usage:
IpAuth::doAuth(array(
'xxx.xxx.xxx.* ',
'yyy.yyy.yyy.* ',
'aaa.bbb.ccc.0/19',
'a.b.c.d',
));
*/
class IpAuth {
public static function doAuth($allowed_ips_pattern=array(),$ip=''){
if(empty($ip)) $ip = $_SERVER['REMOTE_ADDR'];
foreach($allowed_ips_pattern as $ip_pattern){
if(@self::netMatch($ip_pattern, $ip)) return true;
}
//log error
die('IP Not Authorised');
}
/**
* Courtesy:
* http://stackoverflow.com/questions/10421613/match-ipv4-address-given-ip-range-mask
*/
public static function netMatch($network, $ip) {
$network=trim($network);
$orig_network = $network;
$ip = trim($ip);
if ($ip == $network) {
//echo "used network ($network) for ($ip)\n";
return TRUE;
}
$network = str_replace(' ', '', $network);
if (strpos($network, '*') !== FALSE) {
if (strpos($network, '/') !== FALSE) {
$asParts = explode('/', $network);
$network = @ $asParts[0];
}
$nCount = substr_count($network, '*');
$network = str_replace('*', '0', $network);
if ($nCount == 1) {
$network .= '/24';
} else if ($nCount == 2) {
$network .= '/16';
} else if ($nCount == 3) {
$network .= '/8';
} else if ($nCount > 3) {
return TRUE; // if *.*.*.*, then all, so matched
}
}
//echo "from original network($orig_network), used network ($network) for ($ip)\n";
$d = strpos($network, '-');
if ($d === FALSE) {
$ip_arr = explode('/', $network);
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)){
$ip_arr[0].=".0"; // Alternate form 194.1.4/24
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
} else {
$from = trim(ip2long(substr($network, 0, $d)));
$to = trim(ip2long(substr($network, $d+1)));
$ip = ip2long($ip);
return ($ip>=$from and $ip<=$to);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment