There is such a need, according to the user's IP address, locate the user's city.
This article records the article, has no logic. Friends with such needs can be used directly for copying. Directly on the code, do not need to repeat.
<?php header (' content-type:text/html;
Charset=utf-8 ');
function GetIP () {$realip = ';
$unknown = ' unknown '; if (Isset ($_server)) {if (Isset ($_server[' http_x_forwarded_for ']) &&!empty ($_server[' http_x_forwarded_for ') ] && strcasecmp ($_server[' http_x_forwarded_for '), $unknown)) {$arr = explode (', ', $_server[' Http_x_fo
Rwarded_for ']);
foreach ($arr as $ip) {$ip = Trim ($IP);
if ($ip!= ' unknown ') {$realip = $ip;
Break }}else if (Isset ($_server[' http_client_ip ')) &&!empty ($_server[' http_client_ip ']) && ;
STRCASECMP ($_server[' http_client_ip '), $unknown)) {$realip = $_server[' http_client_ip ']; }else if (isset ($_server[' remote_addr ')) &&!empty ($_server[' remote_addr ']) && strcasecmp ($_server['
Remote_addr '], $unknown)) {$realip = $_server[' remote_addr ']; }else{$realip = $unknown;
}else{if (getenv (' http_x_forwarded_for ') && strcasecmp (getenv (' http_x_forwarded_for '), $unknown)) {
$realip = getenv ("Http_x_forwarded_for"); }else if (getenv (' http_client_ip ') && strcasecmp (getenv (' http_client_ip '), $unknown)) {$realip = getenv
("Http_client_ip"); }else if (getenv (' remote_addr ') && strcasecmp (getenv (' remote_addr '), $unknown)) {$realip = getenv ("REMO
Te_addr ");
}else{$realip = $unknown; }} $realip = Preg_match ("/[\d\.] {7,15}/", $realip, $matches)?
$matches [0]: $unknown;
return $realip;
The function getiplookup ($ip = ') {if (empty ($ip)) {$ip = GetIP ();
$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 Address var_dump ($IPINFOS);
Results screenshot:
Using Sina's Open API, the speed of execution is very good.
This article from the CSDN, reprint please mark the source. http://blog.csdn.net/liruxing1715/article/details/28238483