Created
January 9, 2014 05:51
-
-
Save stevenwoodson/8329980 to your computer and use it in GitHub Desktop.
Takes an $ipAddress as a string and an array of IP Addresses and/or IP wildcards $toMatch it with, returns boolean true if a match is found and false otherwise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* IP Address Match | |
* | |
* Takes an $ipAddress as a string and an array of IP Addresses and/or IP wildcards $toMatch it with, returns boolean | |
* true if a match is found and false otherwise | |
* | |
* @param string $ipAddress | |
* @param array $toMatch | |
* @return boolean | |
*/ | |
function ipAddressMatch( $ipAddress, $toMatch ) | |
{ | |
// Loop through the provided $toMatch array and evaluate | |
foreach ($toMatch as $key => $ipPrefix) | |
{ | |
// Full wildcard - always return true | |
if ($ipPrefix == '*') | |
{ | |
return true; | |
} | |
// Partial Wildcard - check syntax and evaluate | |
else if (stristr($ipPrefix, '*')) | |
{ | |
// Make sure there are enough octets provided, if not assume the rest are wildcards and add them | |
if (substr_count($ipPrefix, '.') < 3) | |
{ | |
$octetCount = substr_count($ipPrefix, '.'); | |
for ($i=$octetCount; $i < 3; $i++) | |
{ | |
$ipPrefix .= '.*'; | |
} | |
} | |
// Find the numerical range for this wildcard | |
$ipPrefixFrom = ip2long( str_replace( "*", "0", $ipPrefix ) ); | |
$ipPrefixTo = ip2long( str_replace( "*", "255", $ipPrefix ) ); | |
if (ip2long( $ipAddress ) >= $ipPrefixFrom && ip2long( $ipAddress ) <= $ipPrefixTo) { | |
return true; | |
} | |
} | |
// Standard IP address - check for equality | |
else | |
{ | |
if ($ipAddress == $ipPrefix){ | |
return true; | |
} | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment