Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting IP if it's between a certain IP Range

Tags:

php

I'm using a redirect if the user's ip is between a certain IP range. However, I'm using multiple ip ranges, so I'm wondering the best way to do this. I'm current using this to redirect,

But if the IP ranges are say from 72.122.166.0-72.122.159.266 and 68.61.156.0-68.61.181.255 and 78.121.74.0-78.121.77.255 then how would I do that? Thanks!

like image 682
user1875332 Avatar asked Dec 02 '22 05:12

user1875332


1 Answers

The best way to check IP ranges is to convert the dotted address into a 32-bit number and perform comparisons on that. The ip2long function can do the conversion for you. For example:

$range_start = ip2long("68.61.156.0");
$range_end   = ip2long("68.61.181.255");
$ip          = ip2long($_SERVER['REMOTE_ADDR']);
if ($ip >= $range_start && $ip <= $range_end) {
  // blocked
}

You can put several of these ranges into an array and iterate over it to check multiple ranges.

like image 158
casablanca Avatar answered Dec 19 '22 13:12

casablanca