How to block a range of IPs with php?

4

I have a function in php, but I would not like it to be executed by people in a certain country, how do I get the php script to block a range of IPs?

Example, block the range of US IPs.

It is necessary to be able to add more range of IPs.

    
asked by anonymous 01.09.2016 / 05:51

1 answer

4

You can do this in several ways:

Assuming 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 default mask: 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 default mask: 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 tracks to be locked and make a loop by repeating the block.

Note: Based on responses to iTayb question

    
01.09.2016 / 12:40