通过GeoIP获取ip所属地 (国家,城市,时区,邮编,经纬度等)
来源: http://www.phpandstuff.com/articles/geoip-country-lookup-with-phpGeoIP + PHP
<?php //计时开始 function utime() { $time = explode( " ", microtime() ); $usec = (double)$time; $sec = (double)$time; return $usec + $sec; } $startTimes = utime(); // include the php script // wget -c http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz // gunzip GeoIP.dat.gz include("geoip.inc"); // open the geoip database $gi = geoip_open("GeoIP.dat",GEOIP_STANDARD); // 获取国家代码 $country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']); echo "Your country code is: <strong>$country_code</strong> <br />"; // 获取国家名称 $country_name = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']); echo "Your country name is: <strong>$country_name</strong> <br />"; // close the database geoip_close($gi); //运行结束时间 $endTimes = utime(); $runTimes = sprintf( '%0.4f', ( $endTimes - $startTimes ) ); echo "Processed in " . $runTimes . "second.";?>
注:在本地测试的话因 为$_SERVER['REMOTE_ADDR']和$_SERVER['REMOTE_ADDR']可能是127.0.0.1,所 以输出的内容为空。可以自己带入IP测试
或者 使用某网站的API
API 1.
1. 返回文字
http://api.hostip.info/get_html.php?ip=12.215.42.19&position=true 2. 返回图片
<IMG SRC="http://api.hostip.info/flag.php?ip=12.215.42.19" ALT="IP Address Lookup">
API 2. (需要申请api key ,免费的,类似google)
城市:
http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=74.125.45.100
国家(更快) :
http://api.ipinfodb.com/v3/ip-country/?key=<your_api_key>&ip=74.125.45.100
<div class="section"> Parameter Required Default Value keyYes<empty>API key provided with your free account.ipNoClient IPIP addressformatNorawraw, xml, jsoncallbackNo<empty>Required when using json callback.Please use the appropriate API for your needs. You can help us keep the load low on our servers by making sure that :
[*]If you only need the country name, avoid using the city precision API.
[*]If you track your visitors, avoid querying our API for all your page views (you can store the geolocation in a cookie, see below for an example)
页:
[1]