Skip to content

Instantly share code, notes, and snippets.

@lyquix-owner
Last active March 11, 2023 07:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lyquix-owner/2620da22d927c99d57555530aab3279b to your computer and use it in GitHub Desktop.
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
<?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');
}
@msbarc
Copy link

msbarc commented Mar 18, 2020

array of $ips_allowed should also be modified for range of IPs and subsequently for its logic. this this function may be complete.

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