php實現根據IP地址擷取其所在省市的方法_php執行個體

來源:互聯網
上載者:User
根據現有IP地址擷取其地理位置(省份,城市等)的方法

function GetIpLookup($ip = ''){    if(empty($ip)){      return '請輸入IP地址';   }    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);    if(empty($res)){ return false; }    $jsonMatches = array();    preg_match('#\{.+?\}#', $res, $jsonMatches);    if(!isset($jsonMatches[0])){ return false; }    $json = json_decode($jsonMatches[0], true);    if(isset($json['ret']) && $json['ret'] == 1){      $json['ip'] = $ip;      unset($json['ret']);    }else{      return false;    }    return $json;  } $ipInfos = GetIpLookup('123.125.114.144'); //baidu.com IP地址  var_dump($ipInfos); 

再發一個簡化版的

function getIpAddress(){    $ipContent  = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js");    $jsonData = explode("=",$ipContent);     $jsonAddress = substr($jsonData[1], 0, -1);    return $jsonAddress;  }  $ip_info=json_decode(getIpAddress());  

PHP根據IP地址實現城市切換或跳轉

到這裡,其實問題已經很簡單了,用簡單的js就通通搞定。C段如下:

//根據IP地址跳轉指定頁面js取得城市

var city='<?echo ipCity($xp_UserIp);?>'; //根據IP地址所有城市跳轉到指定頁面

if(city.indexOf("上海市")>=0){

window.location.href="http://shanghai.demo.com/"; }
將開頭的A段代碼和上面的C段代碼分別放在B段代碼的頭和尾,然後我們在需要跳轉的頁面加入以下代碼:


重新整理頁面,是不是達到預想的效果了呢?

以上所述就是本文的全部內容了,希望大家能夠喜歡。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.