Block specific IP block from my website in PHP

前端 未结 8 1506
小蘑菇
小蘑菇 2020-12-05 12:02

I\'d like, for example, block every IP from base 89.95 (89.95..). I don\'t have .htaccess files on my server, so I\'ll have to do it with PHP.

相关标签:
8条回答
  • 2020-12-05 12:35
    $deny = array("111.111.111", "222.222.222", "333.333.333");
    
    if (in_array($_SERVER['REMOTE_ADDR'], $deny)) {
        header("location:http://www.google.com/");
        exit();
    }
    
    0 讨论(0)
  • 2020-12-05 12:36

    Use ip2long() to convert dotted decimal to a real IP address. Then you can do ranges easily.

    Just do ip2long() on the high and low range to get the value, then use those as constants in your code.

    If you're familiar with subnet masking, you can do it like this:

    // Deny 10.12.*.*
    $network = ip2long("10.12.0.0");
    $mask = ip2long("255.255.0.0");
    $ip = ip2long($_SERVER['REMOTE_ADDR']);
    if (($network & $mask) == ($ip & $mask)) {
      die("Unauthorized");
    }
    

    Or if you're familiar with this format 10.12.0.0/16:

    // Deny 10.12.*.*
    $network = ip2long("10.12.0.0");
    $prefix = 16;
    $ip = ip2long($_SERVER['REMOTE_ADDR']);
    if ($network >> (32 - $prefix)) == ($ip >> (32 - $prefix)) {
      die("Unauthorized");
    }
    

    You can turn these into functions and have very manageable code, making it easy to add IP addresses and customize the ranges.

    0 讨论(0)
提交回复
热议问题