php GeoIP庫使用教程樣本

來源:互聯網
上載者:User

php GeoIP庫使用教程

什麼是GepIP ? 所謂GeoIP,就是通過來訪者的IP, 定位他的經緯度,省/地區,省市,甚至街道等位置資訊。這裡面的技術不算難題,關鍵在於有個精準 的資料庫。有了準確的資料來源就奇貨可居賺點小錢,可是發揚合作精神,集體貢獻眾人享用是我們追求的。

GeoIP如何使用? 首先我們需要資料資訊,所以先擷取一個免費的資料庫:GeoIP.dat.gz ,接著解壓得到:GeoIP.dat, 然後就是對資料檔案的按需操作,這邊範例使用的是PHP。 GeoIP + PHP的使用

方法一: 下載 GeoIP 的 PHP 檔案geoip.inc。打包下載

  1. include("geoip.inc.php");
  2. // 開啟資料檔案
  3. $gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
  4. // 擷取國家代碼
  5. $country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
  6. echo "Your country code is: $country_code ";
  7. // 擷取國家名稱
  8. $country_name = geoip_country_name_by_addr($gi, $_SERVER['REMOTE_ADDR']);
  9. echo "Your country name is: $country_name ";
  10. // 關閉檔案
  11. geoip_close($gi);
複製代碼

註:在本地測試的話因 為$_SERVER['REMOTE_ADDR']和$_SERVER['REMOTE_ADDR']可能是127.0.0.1,所 以輸出的內容為空白。可以自己帶入IP測試

方法二: 把 GeoIP 安裝成 PHP 擴充

  1. yum install GeoIP GeoIP-data GeoIP-devel
複製代碼

下載 GeoIP 資料庫

  1. wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
  2. gzip -d GeoLiteCity.dat.gz
  3. mv GeoLiteCity.dat /var/lib/GeoIP/GeoIPCity.dat
複製代碼

下載 GeoIP 的 PECL 擴充 下載地址 http://pecl.php.net/package/geoip

  1. wget -c http://pecl.php.net/get/geoip-1.0.7.tgz
  2. tar -zxvf geoip-1.0.7.tgz
複製代碼

安 裝 GeoIP 的 PECL 擴充

  1. cd geoip-1.0.7
  2. /usr/local/php/bin/phpize
  3. ./configure --with-php-config=/usr/local/php/bin/php-config --with-geoip
  4. make
  5. make install
複製代碼

在 php.ini 裡加上 extension=geoip.so 接著重啟下 php 就行了。

然後,就可以使用 php 手冊中 GeoIP 部份函數了。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.