雖然網路上還有不少可以線上查詢的服務,將 IP 轉成地區資訊,如:
$ curl ipinfo.io/8.8.8.8
{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": null,
"region": null,
"country": "US",
"loc": "38.0000,-97.0000",
"org": "AS15169 Google Inc."
}
不過,大多都有查詢次數的限制,所以,自己架一個來處理吧,在此就挑選 MAXMIND GeoLite2 Free 來使用,其中 FREE 版本就只提供查詢 Country 跟 City 而已。
以 GeoLite2-City.mmdb 為例:
<?php
$target_ip = isset( $_REQUEST['ip'] ) && !empty($_REQUEST['ip']) ? $_REQUEST['ip'] : ( isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL ) ;
// $target_ip = '8.8.8.8';
require( 'MaxMind/Db/Reader.php' );
require( 'MaxMind/Db/Reader/Decoder.php' );
require( 'MaxMind/Db/Reader/InvalidDatabaseException.php' );
require( 'MaxMind/Db/Reader/Metadata.php' );
$reader = new MaxMind\Db\Reader('/path/GeoLite2-City.mmdb');
$record = $reader->get($target_ip);
$reader->close();
echo "<pre>";
print_r( $record );
echo "</pre>";
其中 MaxMind 程式碼可在 github.com/maxmind/MaxMind-DB-Reader-php 下載,此外,在 Ubuntu apt-get 上也有 php5-geoip - GeoIP module for php5 可安裝。
查詢 8.8.8.8:
Array
(
[continent] => Array
(
[code] => NA
[geoname_id] => 6255149
[names] => Array
(
[de] => Nordamerika
[en] => North America
[es] => Norteamérica
[fr] => Amérique du Nord
[ja] => 北アメリカ
[pt-BR] => América do Norte
[ru] => Северная Америка
[zh-CN] => 北美洲
)
)
[country] => Array
(
[geoname_id] => 6252001
[iso_code] => US
[names] => Array
(
[de] => USA
[en] => United States
[es] => Estados Unidos
[fr] => États-Unis
[ja] => アメリカ合衆国
[pt-BR] => Estados Unidos
[ru] => США
[zh-CN] => 美国
)
)
[location] => Array
(
[latitude] => 38
[longitude] => -97
)
[registered_country] => Array
(
[geoname_id] => 6252001
[iso_code] => US
[names] => Array
(
[de] => USA
[en] => United States
[es] => Estados Unidos
[fr] => États-Unis
[ja] => アメリカ合衆国
[pt-BR] => Estados Unidos
[ru] => США
[zh-CN] => 美国
)
)
)
查詢台灣IP:
Array
(
[city] => Array
(
[geoname_id] => 1668341
[names] => Array
(
[de] => Taipeh
[en] => Taipei
[es] => Taipéi
[fr] => Taipei
[ja] => 台北市
[pt-BR] => Taipé
[ru] => Тайбэй
[zh-CN] => 台北市
)
)
[continent] => Array
(
[code] => AS
[geoname_id] => 6255147
[names] => Array
(
[de] => Asien
[en] => Asia
[es] => Asia
[fr] => Asie
[ja] => アジア
[pt-BR] => Ásia
[ru] => Азия
[zh-CN] => 亚洲
)
)
[country] => Array
(
[geoname_id] => 1668284
[iso_code] => TW
[names] => Array
(
[de] => Republik China
[en] => Taiwan
[es] => Taiwán
[fr] => Taïwan
[ja] => 中華民国
[pt-BR] => Taiwan
[ru] => Тайвань
[zh-CN] => 台湾
)
)
[location] => Array
(
[latitude] => 25.0392
[longitude] => 121.525
[time_zone] => Asia/Taipei
)
[registered_country] => Array
(
[geoname_id] => 1668284
[iso_code] => TW
[names] => Array
(
[de] => Republik China
[en] => Taiwan
[es] => Taiwán
[fr] => Taïwan
[ja] => 中華民国
[pt-BR] => Taiwan
[ru] => Тайвань
[zh-CN] => 台湾
)
)
[subdivisions] => Array
(
[0] => Array
(
[geoname_id] => 7280290
[names] => Array
(
[de] => Taipeh
[en] => Taipei
[es] => Taipéi
[ja] => 台北市
[pt-BR] => Taipé
[ru] => Тайбэй
)
)
)
)
沒有留言:
張貼留言