2

I'm currently using some custom code to filter out IP addresses on a Magento store so I can access it whilst in development (maintenance mode).

My current code works fine except it's only for singular IP addresses added to an array.

How would I be best altering this to include cidr format addresses?

My current code is as follows:

    $ip = $_SERVER['REMOTE_ADDR'];
$allowed = array('81.155.118.210','86.136.148.200'); // these are the IP's that are allowed to view the site.

and then further down

    if (file_exists($maintenanceFile) && !in_array($ip, $allowed)) {
    include_once dirname(__FILE__) . '/errors/503.php';
    exit;
}

I would like to be able to use IP addresses such as 195.170.169.0/255 so that I don't have to add them all in singular format however I'm unsure on the best way to add cidr style IP addresses to the array?

Can someone please help?

1 Answer 1

1

You can use the following method I found on the PHP.net website:

  function ipCIDRCheck ($IP, $CIDR) {
    list ($net, $mask) = split ("/", $CIDR);

    $ip_net = ip2long ($net);
    $ip_mask = ~((1 << (32 - $mask)) - 1);

    $ip_ip = ip2long ($IP);

    $ip_ip_net = $ip_ip & $ip_mask;

    return ($ip_ip_net == $ip_net);
  }

And then do:

$ip = $_SERVER['REMOTE_ADDR'];
$allowed = "195.170.169.0/255";
if (file_exists($maintenanceFile) && !ipCIDRCheck($ip, $allowed)) {
    include_once dirname(__FILE__) . '/errors/503.php';
    exit;
}

Edit:

if you need this to work for both your array and your CIDR you can do:

$ip = $_SERVER['REMOTE_ADDR'];
$allowed = array('81.155.118.210','86.136.148.200');
$cidr = "195.170.169.0/255";
if (file_exists($maintenanceFile) && !in_array($ip, $allowed) && !ipCIDRCheck($ip, $cidr)) {
    include_once dirname(__FILE__) . '/errors/503.php';
    exit;
}
3
  • Thank you for this Raphael. I did a quick Google and couldn't find an example for an array. However this doesn't seem to work for an array either? Your code works, however when used as an array it allows access to IP addresses outside the range. I altered your code to this: $allowed = array('81.155.118.211/32','86.136.148.201/32'); Which are both outside my IP address and I can get access? An array is important as I will need an IP address for myself plus a range for SagePay servers (for example). Thank you Oct 10, 2016 at 13:40
  • @user2314311 see my edit if you wanna use both the array and the cidr Oct 10, 2016 at 13:42
  • Brilliant. Works perfectly using your edit. Thank you very much Raphael! Oct 10, 2016 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.