Php 按国家/地区ip范围阻止用户注册

Php 按国家/地区ip范围阻止用户注册,php,mysql,Php,Mysql,我在MYSQL中有下表 CREATE TABLE IF NOT EXISTS `countryip` ( `ip_from` bigint(10) unsigned NOT NULL DEFAULT '0', `ip_to` bigint(10) unsigned NOT NULL DEFAULT '0', `country_iso2` varchar(2) COLLATE utf8_bin NOT NULL DEFAULT '', `country_iso3` varchar(3) COLLA

我在MYSQL中有下表

CREATE TABLE IF NOT EXISTS `countryip` (
`ip_from` bigint(10) unsigned NOT NULL DEFAULT '0',
`ip_to` bigint(10) unsigned NOT NULL DEFAULT '0',
`country_iso2` varchar(2) COLLATE utf8_bin NOT NULL DEFAULT '',
`country_iso3` varchar(3) COLLATE utf8_bin NOT NULL DEFAULT '',
`country_name` varchar(32) COLLATE utf8_bin NOT NULL,
KEY `ip_from` (`ip_from`,`ip_to`)) 
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
在这里,我添加了全世界所有国家的知识产权范围

我想在php中创建一个脚本,将用户ip与来自该数据库的ip范围进行比较,然后返回一条消息。 从我所理解的开始,我需要声明

<?php
    mysql_select_db("database_name")   or die(mysql_error());
$ip = $_SERVER['REMOTE_ADDR'];
    $query = mysql_query("SELECT `IP` FROM `ban_ip` WHERE `IP` = '$ip'"); // this works only if i have the single static ip in the dbs, but now i have the ip range
    if (mysql_num_rows($query) > 0)
    {
echo ' <!DOCTYPE html> <html> <head> <script type="text/javascript"> alert("You are not allowed to access this website"); window.location.replace("index.php"); </script> </head> <body> </body> </html>';
    }
以便能够比较用户IP和IP范围

IP FROM列,TO IP列如下所示 16777216, 16777471,
为了找出ip,有一个与ip=256+B类*256+C类*256*256+D类*256*256*256类似的公式,我知道这不是你问题的直接答案,但我最近使用了这个API


使用JSON非常容易,而且可以从服务器快速回复。它是免费的,可以试用,可以在数据库中节省一些存储空间。

您可以对指定的表使用以下SQL查询:

SELECT `country_iso2` FROM `countryip` WHERE `ip_from` <= inet_aton('$ip') AND ip_to >= inet_aton('$ip')
从'countryip'中选择'country\u iso2',其中'ip\u FROM`=inet\u aton('$ip'))

这将为您指定的IP地址选择两个字符的国家/地区ISO代码。从这里开始,只需将ISO代码与禁用国家/地区代码表中的条目进行比较。

这不是问题的直接答案,但根据我的经验,自己维护IP数据库有点麻烦

为此,我使用了MaxMind的免费GeoLite2数据库,因为它经常更新并提供非常精确的结果:


如果您关心PHP扩展API,我建议您使用它。使用PHP(CAPI)扩展,每秒可以获得700万次以上的查询。MySQL没有针对这些类型的查询进行调优,通过SQL管理不断变化的IP地址更新可能成为一个难点。Maxmind每月发布更新,您可以轻松下载

我在这里介绍如何编译扩展,以及如何使用PHP中的mmdb数据库通过iso-3316 2字符代码限制国家:

SELECT `country_iso2` FROM `countryip` WHERE `ip_from` <= inet_aton('$ip') AND ip_to >= inet_aton('$ip')