取客户端ip其实不是个简单的活儿,因为存在Ip欺骗,和代理问题,所以获取客户端的IP的真实性会打折扣的,不能百分百准确.但是我们还是尽量找一个比较完善的获取客户端真正ip方法.使用php获取IP的方法能找到很多.
php获取用户(客户端)真实IP地址的三种方法
01 | function get_real_ip(){ |
03 | if(!empty($_SERVER['HTTP_CLIENT_IP'])){ |
04 | $ip=$_SERVER['HTTP_CLIENT_IP']; |
06 | if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ |
07 | $ips=explode (', ', $_SERVER['HTTP_X_FORWARDED_FOR']); |
08 | if($ip){ array_unshift($ips, $ip); $ip=FALSE; } |
09 | for ($i=0; $i < count($ips); $i++){ |
10 | if(!eregi ('^(10│172.16│192.168).', $ips[$i])){ |
16 | return ($ip ? $ip : $_SERVER['REMOTE_ADDR']); |
第二种方法:
01 | function get_real_ip(){ |
04 | if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ |
05 | $realip=$_SERVER['HTTP_X_FORWARDED_FOR']; |
06 | }else if(isset($_SERVER['HTTP_CLIENT_IP'])){ |
07 | $realip=$_SERVER['HTTP_CLIENT_IP']; |
09 | $realip=$_SERVER['REMOTE_ADDR']; |
12 | if(getenv('HTTP_X_FORWARDED_FOR')){ |
13 | $realip=getenv('HTTP_X_FORWARDED_FOR'); |
14 | }else if(getenv('HTTP_CLIENT_IP')){ |
15 | $realip=getenv('HTTP_CLIENT_IP'); |
17 | $realip=getenv('REMOTE_ADDR'); |
第三种方法,摘自DISCUZ,应该还不错吧!
04 | if(!empty($_SERVER['HTTP_CLIENT_IP'])){ |
05 | return is_ip($_SERVER['HTTP_CLIENT_IP'])?$_SERVER['HTTP_CLIENT_IP']:$ip; |
06 | }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ |
07 | return is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$ip; |
09 | return is_ip($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:$ip; |
13 | $ip=explode('.',$str); |
14 | for($i=0;$i<count($ip);$i++){ |
19 | return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$str); |