六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 40|回复: 0

通过GeoIP获取ip所属地 (国家,城市,时区,邮编,经纬度等)

[复制链接]

升级  58.8%

250

主题

250

主题

250

主题

进士

Rank: 4

积分
794
 楼主| 发表于 2013-1-26 15:04:22 | 显示全部楼层 |阅读模式
来源: http://www.phpandstuff.com/articles/geoip-country-lookup-with-php
 
GeoIP + PHP

<?php    //计时开始    function utime() {        $time = explode( " ", microtime() );        $usec = (double)$time[0];        $sec = (double)$time[1];        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)
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表