How to detect country and city using PHP, GeoIP and Maxmind?

房东的猫 提交于 2019-11-29 02:44:34
T.Todua

Method 1: Using Online services

Method 2: Using Maxmind GeoIP_V2

How I did it: let's say, create a folder named "My_Folder" and inside it:

  1. create folder GeoIp2 and put in it content of this "SRC" folder (download).
  2. put MaxMind folder (download, from "SRC" folder).
  3. place i.e. GeoLite2-Country.mmdb (download).

then, in My_Folder create a example.php file and put this code:

$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

p.s. other examples found at: https://github.com/maxmind/GeoIP2-php

for reference the code should look like this first download php class pack http://www.maxmind.com/download/geoip/api/php/php-1.11.tar.gz you will need this files

geoip.inc
geoipcity.inc
geoipregionvars.php

put them in same directory your code to get city and other info is this

<?php
include("geoipcity.inc");
include("geoipregionvars.php");
$ip = "144.3.87.197"; 
$gi = geoip_open("GeoLiteCity.dat",GEOIP_STANDARD);
$record= geoip_record_by_addr($gi,$ip);
echo 'City Name'.$record->city . "\n";
geoip_close($gi);
?>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!