Sample code for PHP to judge locale name information according to IP

  • 2021-01-18 06:19:40
  • OfStack

Look at the code
 
<?php 
header("Content-type: text/html; charset=utf-8"); 
function getIP(){ 
if (isset($_SERVER)) { 
if (isset($_SERVER[HTTP_X_FORWARDED_FOR])) { 
$realip = $_SERVER[HTTP_X_FORWARDED_FOR]; 
} elseif (isset($_SERVER[HTTP_CLIENT_IP])) { 
$realip = $_SERVER[HTTP_CLIENT_IP]; 
} else { 
$realip = $_SERVER[REMOTE_ADDR]; 
} 
} else { 
if (getenv("HTTP_X_FORWARDED_FOR")) { 
$realip = getenv( "HTTP_X_FORWARDED_FOR"); 
} elseif (getenv("HTTP_CLIENT_IP")) { 
$realip = getenv("HTTP_CLIENT_IP"); 
} else { 
$realip = getenv("REMOTE_ADDR"); 
} 
} 
return $realip; 
} 

$ip = getIP(); 

//  Use sina interface according to ip Query the location of the region  
/* $res0 = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip"); 
$res0 = json_decode($res0); 
print_r($res0); 
echo "<br />"; */ 

//  Use taobao interface according to ip Query the location of the region  
$res1 = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=$ip"); 
$res1 = json_decode($res1); 
/* print_r($res1); */ 

How to read the data, see below.
 
$array = get_object_vars($res1);// Assign value to an array  
foreach($array as $value){ 
echo $value->region."<br />"; 
echo $value->city."<br />"; 
echo $value->ip."<br />"; 
} 
?> 

// Or use object data access  echo $res1->data->city; 

Related articles: