How to block a range of Ips with php?

Asked

Viewed 1,136 times

5

I have a function in php, but I wouldn’t like it to be run by people from a certain country, as I do for the php script to block a range of Ips?

Example, block the US IP range.

You need to be able to add more range of Ips.

  • Would have some specific reason not to block using the own nginx or apache? They tend to be much more efficient for this activity.

  • Yes, the dynamic lock @Inkeliz

  • You can use Geoip for this, http://php.net/manualen/function.geoip-country-code-by-name.php. This function is "obsolete" because it does not support Ipv6 natively. It returns the countries in ISO 3166 as you can see in http://dev.maxmind.com/geoip/legacy/codes/iso3166/. Then just compare the geolocation of the user’s IP with what you want. Just remember that this is NOT 100% accurate!

1 answer

5


You can do it in many ways:

Suppose you want to block the track: 90.25..

1) Using strpos:

if(strpos($_SERVER['REMOTE_ADDR'], "90.25") === 0)){ // se ip começa com 90.25
    echo 'bloqueado';
    exit;
}

2) Using ip2long with mask in pattern: 255.255.0.0

$rede = ip2long("90.25.0.0");
$mascara = ip2long("255.255.0.0");
$ip = ip2long($_SERVER['REMOTE_ADDR']);
if (($mascara & $mascara) == ($ip & $mascara)) {
        echo 'bloqueado';
        exit;
}

3) Using ip2long with mask on pattern: 255.255.0.0/16

$rede = ip2long("90.25.0.0");
$prefixo = 16;
$ip = ip2long($_SERVER['REMOTE_ADDR']);
if ($rede >> (32 - $prefixo )) == ($ip >> (32 - $prefixo )) {
     echo 'bloqueado';
     exit;
}

To block multiple tracks, create a array of the tracks to be blocked and make a loop repeating the block.

Note: Based on responses to iTayb

Browser other questions tagged

You are not signed in. Login or sign up in order to post.