今天,就討論一下在PHP中如何獲取用戶IP地址、PHP根據IP判斷用戶所在城市以及PHP根據IP實現城市切換或跳轉的問題。
根據現有IP地址獲取其地理位置(省份,城市等)的方法
- function GetIpLookup($ip = ''){
- if(emptyempty($ip)){
- return '請輸入IP地址';
- }
- $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
- if(emptyempty($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=''; //根據IP地址所有城市跳轉到指定頁面
if(city.indexOf("上海市")>=0){
window.location.href="http://shanghai.demo.com/"; }
將開頭的A段代碼和上面的C段代碼分別放在B段代碼的頭和尾,然后我們在需要跳轉的頁面加入以下代碼:
刷新頁面,是不是達到預想的效果了呢?
以上所述就是本文的全部內容了,希望大家能夠喜歡。
新聞熱點
疑難解答