问题
I wanted small tutorial how to detect an IP's city or country. I heard that MaxMind GeoIp was good for it.
回答1:
Method 1: Using Online services
- http://www.geoplugin.net/php.gp?ip=123.123.123.123
- http://ip-api.com/php/123.123.123.123
- http://ipinfo.io/123.123.123.123
- http://api.codehelper.io/ips/?callback=codehelper_ip_callback&ip=123.123.123.123
Method 2: Using Maxmind GeoIP_V2
How I did it: let's say, create a folder named "My_Folder" and inside it:
- create folder
GeoIp2
and put in it content of this "SRC" folder (download). - put
MaxMind
folder (download, from "SRC" folder). - 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
回答2:
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);
?>
回答3:
MaxMind is a Massachusetts-based digital mapping company that provides location data for IP addresses. [MaxMind] was founded in 2002 by Thomas "TJ" Mather and is based in Waltham,so here is simple tutorial for How to detect country and city using PHP, GeoIP and [Maxmind].
1) first need to user ip address you can use according to your platform like app or web or there respective language.
2)then in backend you make a curl request with any of these given links and you get full location array with country , state ,city,cordinates etc.
http://www.geoplugin.net/php.gp?ip=123.123.123.123
http://ip-api.com/php/123.123.123.123
http://ipinfo.io/123.123.123.123
http://api.codehelper.io/ips/?callback=codehelper_ip_callback&ip=12
来源:https://stackoverflow.com/questions/20642598/how-to-detect-country-and-city-using-php-geoip-and-maxmind