This article mainly to share with you how PHP based on IP address to obtain the city, this article mainly in the form of code, I hope to help everyone.
<?phpheader (' 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_for Warded_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 ("Remot E_addr "); }else{$realip = $unknown; }} $realip = Preg_match ("/[\d\.") {7,15}/", $realip, $matches)? $matches [0]: $unknown; return $realip;} 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 鍦 Board from Var_dump ($ipInfos);? >