如何使用PHP,GeoIP和Maxmind检测国家和城市?

T.T*_*dua 2 maxmind

我想要一些小教程如何检测IP的城市或国家.我听说MaxMind GeoIp对它有好处.

T.T*_*dua 11

方法1:使用在线服务

方法2:使用Maxmind GeoIP_V2

我是怎么做到的:让我们说,创建一个名为" My_Folder " 的文件夹并在其中:

  1. 创建文件夹GeoIp2并将其放入此"SRC"文件夹的内容(下载).
  2. MaxMind文件夹(从"SRC"文件夹下载).
  3. 地方即GeoLite2-Country.mmdb(下载).

然后,在My_Folder创建example.php文件并放入此代码:

$user_ip='123.123.123.123';

spl_autoload_register('func888'); function func888($class){ include_once(str_replace(array('/','\\'), DIRECTORY_SEPARATOR, dirname(__file__)."/$class.php")) ;}
use GeoIp2\Database\Reader; 
//you can do it for "city" too.. just everywhere change phrase "country" with "city".
try{
    $reader = new Reader(dirname(__file__)."/GeoLite2-Country.mmdb");
    $record = $reader->country($user_ip);
    $reader->close();
    $country_name =  $record->raw['country']['names']['en'];
} catch ( GeoIp2\Exception\AddressNotFoundException $e ){    $country_name = 'not_found';  }

echo $country_name;
// RESULTS -------------- > China
Run Code Online (Sandbox Code Playgroud)

ps其他示例发现于:https://github.com/maxmind/GeoIP2-php