还是在OutOfMemory上看到的一段代码,自己修改了一下,其中的unescape()函数值得学习和搜藏,另一点就是从Sina的iplookup库中获取地理位置等信息比较有用:
<?php /** * 获取客户端+服务端IP及地理位置信息 Sina iplookup **/ //取得地理位置信息 function iplookup($ip=1){ if($ip){ //客户端 $userip = getClientIP(); //客户端IP }else{ //服务端 $domain = $_SERVER['HTTP_HOST']; $userip = gethostbyname($domain); } //$userip = (getClientIP()=='127.0.0.1')?'107.170.214.214':getClientIP(); //返回Sina地理位置信息 $json=@file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip='.$userip); $patterns = array(); $patterns[0] = '/var remote_ip_info = /'; $patterns[1] = '/;/'; $patterns[2] = '/\Wu/'; $find = array(); $find[0] = ""; $find[1] = ""; $find[2] = "%u"; $json = preg_replace($patterns, $find, $json); //过滤多余字符 $json_arr = json_decode($json,true); return $json_arr; } //获取客户端IP function getClientIP(){ if(getenv('HTTP_CLIENT_IP')&&strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')){ $ip=getenv('HTTP_CLIENT_IP'); } elseif(getenv('HTTP_X_FORWARDED_FOR')&&strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')){ $ip=getenv('HTTP_X_FORWARDED_FOR'); } elseif(getenv('REMOTE_ADDR')&&strcasecmp(getenv('REMOTE_ADDR'),'unknown')){ $ip=getenv('REMOTE_ADDR'); } elseif(isset($_SERVER['REMOTE_ADDR'])&&$_SERVER['REMOTE_ADDR']&&strcasecmp($_SERVER['REMOTE_ADDR'],'unknown')){ $ip=$_SERVER['REMOTE_ADDR']; } $ip=preg_replace("/^([d.]+).*/","1",$ip); return $ip; } /** * 模拟JS里的unescape * echo unescape('%u4e2d%u56fd'); */ function unescape($str) { $str = rawurldecode($str); preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U", $str, $r); $ar = $r[0]; foreach($ar as $k=>$v) { if(substr($v,0,2) == "%u"){ $ar[$k] = iconv("UCS-2", "utf-8//IGNORE", pack("H4",substr($v,-4))); } elseif(substr($v,0,3) == ""){ $ar[$k] = iconv("UCS-2", "utf-8", pack("H4",substr($v,3,-1))); } elseif(substr($v,0,2) == "&#"){ echo substr($v,2,-1).""; $ar[$k] = iconv("UCS-2", "utf-8", pack("n",substr($v,2,-1))); } } return join("",$ar); } $iplookup = iplookup(); //iplookup()的参数为0则是获取服务器端IP,默认为获取客户端IP echo "IP:".getClientIP()."<br>"; echo '返回状态:'.$iplookup['ret']."<br>"; echo 'IP范围Strat:'.$iplookup['start']."<br>"; echo 'IP范围End:'.$iplookup['end']."<br>"; echo '国家:'.unescape($iplookup['country'])."<br>"; echo '省份:'.unescape($iplookup['province'])."<br>"; echo '城市:'.unescape($iplookup['city'])."<br>"; echo '区/县:'.unescape($iplookup['district'])."<br>"; echo '线路:'.unescape($iplookup['isp'])."<br>"; echo '类型:'.$iplookup['type']."<br>"; echo '描写:'.$iplookup['desc']."<br>"; print_r($iplookup);
从Sina的iplookup库中获取结果后,需要先用preg_replace()函数过滤掉多余字符然后再交给json_decode()函数处理,而且其中数组下标为country、province、city、district、isp的内容是Unicode编码的,也可以用之前文章中说的方法进行解码(Unicode编码解码的PHP脚本[bak])。