PHPで IPアドレスから国や地域を取得できるように、Geolocation関連の GeoIP ライブラリおよび、PECL::geoip をインストールします。(2012/10/20作成)
jill111 / Pixabay
PECL::Package::geoip
http://pecl.php.net/package/geoip
0.環境
$ php -v PHP 5.3.10 (cli) (built: Feb 4 2012 07:16:03) Copyright (c) 1997-2012 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
1.GeoIP C ライブラリインストール
$ wget http://www.maxmind.com/download/geoip/api/c/GeoIP.tar.gz $ tar zxvf GeoIP.tar.gz $ cd GeoIP-1.4.8 $ ./configure $ make $ sudo make install
【参考】 ライブラリ依存関係の解決
Libtool library used but `LIBTOOL' is undefined -> yum install libtool autoreconf -> yum install autoconf aclocal -> yum install automake
2.GeoLite Country, GeoLite City バイナリデータを配置
$ wget http://www.maxmind.com/download/geoip/database/GeoIPv6.dat.gz $ wget http://www.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz $ gzip -d GeoIPv6.dat.gz $ gzip -d GeoLiteCity.dat.gz $ sudo cp GeoIPv6.dat /usr/local/share/GeoIP/ $ sudo cp GeoLiteCity.dat /usr/local/share/GeoIP/GeoIPCity.dat
※RPMで「GeoIP」をインストールした場合、「geoip_record_by_name()」を実行時下記のエラーとなります。その場合は「GeoIPCity.dat」を「/usr/share/GeoIP」配下にシンボリックリンクします。
$ php a.php PHP Warning: geoip_record_by_name(): Required database not available at /usr/share/GeoIP/GeoIPCity.dat. in /tmp/a.php on line 2 $ sudo ln -s /usr/local/share/GeoIP/GeoIPCity.dat /usr/share/GeoIP/GeoIPCity.dat
3.PECL::Package::geoip インストール
$ sudo pecl install geoip You should add "extension=geoip.so" to php.ini extension=geoip.so $ sudo /etc/init.d/httpd restart
4.使い方
$ cat a.php
<?php $record = geoip_record_by_name('www.offline-net.com'); print_r($record);
$ php a.php
Array ( [continent_code] => AS [country_code] => JP [country_code3] => JPN [country_name] => Japan [region] => 40 [city] => Tokyo [postal_code] => [latitude] => 35.685001373291 [longitude] => 139.75140380859 [dma_code] => 0 [area_code] => 0 )
以上