-
-
Save tott/7684443 to your computer and use it in GitHub Desktop.
/** | |
* Check if a given ip is in a network | |
* @param string $ip IP to check in IPV4 format eg. 127.0.0.1 | |
* @param string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed | |
* @return boolean true if the ip is in this range / false if not. | |
*/ | |
function ip_in_range( $ip, $range ) { | |
if ( strpos( $range, '/' ) == false ) { | |
$range .= '/32'; | |
} | |
// $range is in IP/CIDR format eg 127.0.0.1/24 | |
list( $range, $netmask ) = explode( '/', $range, 2 ); | |
$range_decimal = ip2long( $range ); | |
$ip_decimal = ip2long( $ip ); | |
$wildcard_decimal = pow( 2, ( 32 - $netmask ) ) - 1; | |
$netmask_decimal = ~ $wildcard_decimal; | |
return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) ); | |
} |
Really useful, Thanks!
Great! Saved me some priceless time!
Thanks a lot.
Little optimization: You should do the strpos check with "===" else php matches the first position too, because 0 == false.
Thank you!
Very good. Thank you.
The ===
is still not fixed. Else thank you!
THAANKSS MAN. very good!
Thanks!
thx - nice peace!
Very nice... thank you for this code
A word of thanks.
See also the implementation by cloudflare, supporting ipv4 and v6: https://github.com/cloudflare/CloudFlare-Tools/blob/master/cloudflare/ip_in_range.php
Thanks for the link! This is what I need.
Thanks a lot !
Thank you.. useful for a lot of projects
Thanks!
good stuff
how to find ipv6 in range.
Great Job.
this modification can be made
if (strpos($range, '/' ) == false) { return $ip == $range; }
Thanks!