Skip to content

Instantly share code, notes, and snippets.

@hugodotlau
Created June 8, 2012 03:27
Show Gist options
  • Save hugodotlau/2893372 to your computer and use it in GitHub Desktop.
Save hugodotlau/2893372 to your computer and use it in GitHub Desktop.
ipfilter form array()
<?php
/**
* Checks to see if the user IP is allowed by {@link ipFilters}.
* @param string $ip the user IP
* @return boolean whether the user IP is allowed by {@link ipFilters}.
*/
protected function allowIp($ip)
{
foreach ($this->ipFilters as $filter)
{
$filter = trim($filter);
// normal or incomplete IPv4
if (preg_match('/^[\d\.]*\*?$/', $filter)) {
$filter = rtrim($filter, '*');
if (strncmp($ip, $filter, strlen($filter)) === 0)
{
return true;
}
}
// CIDR
else if (preg_match('/^([\d\.]+)\/(\d+)$/', $filter, $match))
{
if (self::matchIpMask($ip, $match[1], $match[2]))
{
return true;
}
}
// IPv6
else if ($ip === $filter)
{
return true;
}
}
return false;
}
/**
* Check if an IP matches a CIDR mask.
*
* @param integer|string $ip IP to check.
* @param integer|string $matchIp Radical of the mask (e.g. 192.168.0.0).
* @param integer $maskBits Size of the mask (e.g. 24).
*/
protected static function matchIpMask($ip, $maskIp, $maskBits)
{
$mask =~ (pow(2, 32-$maskBits)-1);
if (false === is_int($ip))
{
$ip = ip2long($ip);
}
if (false === is_int($maskIp))
{
$maskIp = ip2long($maskIp);
}
if (($ip & $mask) === ($maskIp & $mask))
{
return true;
} else {
return false;
}
}
@hugodotlau
Copy link
Author

From: YiiDebugToolbar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment