Home  >  Article  >  Backend Development  >  PHP implements city switching or jump based on IP

PHP implements city switching or jump based on IP

墨辰丷
墨辰丷Original
2018-06-11 11:49:302645browse

This article mainly introduces PHP to implement city switching or jump based on IP. Friends who are interested can refer to it. I hope it will be helpful to everyone.

How to obtain the geographical location (province, city, etc.) based on the existing IP address

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);

Send a simplified version

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 implements city switching based on IP address Or jump to

. In fact, the problem is very simple. You can solve it all with simple js. Section C is as follows:

//根据IP地址跳转指定页面js取得城市
var city=&#39;<?echo ipCity($xp_UserIp);?>&#39;; //根据IP地址所有城市跳转到指定页面
if(city.indexOf("上海市")>=0){
         window.location.href="http://shanghai.demo.com/"; }

Place the beginning A section code and the above C section code at the beginning and end of the B section code respectively, and then we add the following code to the page that needs to be jumped:

<script src="/ipcity/ipaddress.php" type="text/javascript" language="javascript"></script>

Refresh the page, is it achieving the desired effect?

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Polymorphism in PHP

The principle of PHP event mechanism

How to operate session and database in php

The above is the detailed content of PHP implements city switching or jump based on IP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn