Home > Article > Backend Development > PHP implements the method of obtaining the province and city where the IP is located based on the IP address. The province and city where the IP is located_PHP tutorial
The method of obtaining 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 or jump based on IP address
At this point, the problem is actually very simple. It can be solved with simple js. Paragraph C is as follows:
//Jump to the specified page to get the city based on the IP address
var city='64164d0d2563952345500c0ea66c75fe'; //Jump to the specified page in all cities based on IP address
if(city.indexOf("Shanghai City")>=0){
window.location.href="http://shanghai.demo.com/"; }
Place the code A at the beginning and the code C above at the beginning and end of the code B respectively, and then we add the following code to the page that needs to be jumped:
780c2ce334ef204d6678887340170e2f2cacc6d41bbb37262a98f745aa00fbf0
Refresh the page. Does it achieve the desired effect?
The above is the entire content of this article, I hope you all like it.