Last active
September 19, 2024 01:20
-
-
Save lyquix-owner/2620da22d927c99d57555530aab3279b to your computer and use it in GitHub Desktop.
PHP function to check if it matches allowed IP addresses and subnets
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 to check | |
$ip_check = $_SERVER['REMOTE_ADDR']; | |
// Array of allowed IPs and subnets, both IPv4 and IPv6 | |
$ips_allowed = array( | |
'192.30.252.0/22' | |
'2620:112:3000::/44' | |
'192.168.16.104' | |
); | |
// Flag for IP match allowed list | |
$ip_match = false; | |
foreach($ips_allowed as $ip_allow) { | |
// If IP has / means CIDR notation | |
if(strpos($ip_allow, '/') === false) { | |
// Check Single IP | |
if(inet_pton($ip_check) == inet_pton($ip_allow)) { | |
$allow = true; | |
break; | |
} | |
} | |
else { | |
// Check IP range | |
list($subnet, $bits) = explode('/', $ip_allow); | |
// Convert subnet to binary string of $bits length | |
$subnet = unpack('H*', inet_pton($subnet)); // Subnet in Hex | |
foreach($subnet as $i => $h) $subnet[$i] = base_convert($h, 16, 2); // Array of Binary | |
$subnet = substr(implode('', $subnet), 0, $bits); // Subnet in Binary, only network bits | |
// Convert remote IP to binary string of $bits length | |
$ip = unpack('H*', inet_pton($ip_check)); // IP in Hex | |
foreach($ip as $i => $h) $ip[$i] = base_convert($h, 16, 2); // Array of Binary | |
$ip = substr(implode('', $ip), 0, $bits); // IP in Binary, only network bits | |
// Check network bits match | |
if($subnet == $ip) { | |
$allow = true; | |
break; | |
} | |
} | |
} | |
if(!$allow) { | |
die('IP not allowed'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
array of $ips_allowed should also be modified for range of IPs and subsequently for its logic. this this function may be complete.