php 獲取公網IP地址、定位所在城市

本地localhost、127.0.0.1時,均能獲取外網IP地址。

<?php
    //獲取外網IP的地址,以下兩個均測試成功
    //$url = 'http://tool.huixiang360.com/zhanzhang/ipaddress.php';
    $url = 'http://city.ip138.com/ip2city.asp';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $a  = curl_exec($ch);
    preg_match('/\[(.*)\]/', $a, $ip);
    //echo $ip[1];

    //根據IP地址定位所在城市
    ①使用淘寶IP庫
    $res = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=$ip");
    $res = json_decode($res,true);
    print_r($res);
?>

返回結果如圖:

    ②使用新浪IP庫
    $res = @file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip");
    $res = json_decode($res,true);
    print_r($res); 
?>

返回結果如圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章