I wanted small tutorial how to detect an IP's city or country. I heard that MaxMind GeoIp was good for it.
T.Todua
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
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);
?>
来源:https://stackoverflow.com/questions/20642598/how-to-detect-country-and-city-using-php-geoip-and-maxmind