欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

增强记忆的好方法,做笔记---php获取用户ip地址及所在城市

程序员文章站 2022-06-28 21:03:07
增强对知识的记忆最笨得方法也是最好的办法就是做笔记,从今天开始记录我的php工作、学习笔记。 1、获取浏览者的ip地址及所在城市的代码 首先是获取浏览者的ip地址的函...

增强对知识的记忆最笨得方法也是最好的办法就是做笔记,从今天开始记录我的php工作、学习笔记。
1、获取浏览者的ip地址及所在城市的代码
首先是获取浏览者的ip地址的函数
function getrealip() { 
       if (!emptyempty($_server['http_client_ip'])) {  //check ip from share internet 
         $ip=$_server['http_client_ip']; 
       } elseif (!emptyempty($_server['http_x_forwarded_for'])) {  //to check ip is pass from proxy 
         $ip=$_server['http_x_forwarded_for']; 
       } else { 
         $ip=$_server['remote_addr']; 
       } 
       return $ip; 
    }
获取ip地址后,访问的提供的一个api取得所在城市
 
function ips($ip){ 
    $str=file_get_contents("?ip={$ip}&action=2">http://www.ip138.com/ips.asp?ip={$ip}&action=2"); 
    preg_match("/<ul class=\"ul1\">(.*)<\/ul>/",$str,$m); 
    $pstr=str_replace("</li>","",$m[1]); 
    $arr=explode("<li>",$pstr); 
    array_shift($arr); 
    return $arr; 
}
 2、通过腾讯提供的api获取ip及所在城市(注意:只能获取服务器的地址,方法获取浏览者的信息有些遗憾)。
个人觉得这个函数非常好,可惜只呢获取服务器所在的信息。
 
function get_ip_place(){   
$ip=file_get_contents("");   
$ip=str_replace('"',' ',$ip);   
$ip2=explode("(",$ip);   
$a=substr($ip2[1],0,-2);   
$b=explode(",",$a);   
return $b;   
}   
$ip=get_ip_place();   
print_r($ip);   
 
 基础知识补充:
$_server['http_client_ip']:获取代理的ip(有可能存在,可伪造)
$_server['http_x_forwarded_for']:用户是在哪个ip使用的代理(有可能存在,也可以伪造,什么的函数获取的真实ip地址就是用这个常用变量取得的)
$_server['remote_name']:访问端(有可能是用户,有可能是代理的)ip

作者“volley”