1. 程式人生 > 實用技巧 >PHP安裝GeoIP擴充套件根據IP獲取訪客所在國家/城市/經緯度等資訊

PHP安裝GeoIP擴充套件根據IP獲取訪客所在國家/城市/經緯度等資訊

>>> hot3.png



http://php.net/manual/zh/ref.geoip.php
sudo apt-get install libgeoip-dev
pecl install geoip-1.1.0 注意:Beta版要指定版本號.如果是apt安裝的PHP,直接安裝php5-geoip這個包即可.
php.ini中加入:
extension=geoip.so
geoip.custom_directory="/usr/share/GeoIP"

免費下載GeoLiteCity資料庫(解壓後18MB):
http://dev.maxmind.com/geoip/legacy/install/city/

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

測試:
php -a
<?php
print_r(geoip_record_by_name('106.37.165.80')); 回車後按Ctrl+D執行
Array
(
[continent_code] => AS
[country_code] => CN
[country_code3] => CHN
[country_name] => China //國家
[region] => 22
[city] => Beijing //城市
[postal_code] =>
[latitude] => 39.928901672363 //緯度
[longitude] => 116.38829803467 //經度
[dma_code] => 0
[area_code] => 0
)

在命令列用geoiplookup檢視IP資訊:
traceroute www.oschina.net 可見IP地址 61.145.122.155
sudo apt-get install geoip-bin geoip-database
geoiplookup 61.145.122.155 -f /usr/share/GeoIP/GeoIP.dat
GeoIP Country Edition: CN, China
geoip-database提供的GeoIP.dat只能精確到國家.

geoiplookup 61.145.122.155 -f /usr/share/GeoIP/GeoIPCity.dat
GeoIP City Edition, Rev 1: CN, 30, Guangdong, Guangzhou, N/A, 23.116699, 113.250000, 0, 0
從maxmind官網下的資料庫GeoLiteCity則資訊更詳細.

geoiplookup 61.145.122.155 則同時顯示上述兩個資料庫的資訊.

補充:
PHP輕鬆實現"附近的人"功能,根據IP確定經緯度,根據經緯度計算距離

轉載於:https://my.oschina.net/eechen/blog/374188