php 获取客户端ip

方法一:(c)

 1 function get_ip(){
 2     $ip=false;
 3     if(!empty($_SERVER['HTTP_CLIENT_IP'])){
 4         $ip=$_SERVER['HTTP_CLIENT_IP'];
 5     }
 6     if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
 7         $ips=explode (', ', $_SERVER['HTTP_X_FORWARDED_FOR']);
 8         if($ip){ array_unshift($ips, $ip); $ip=FALSE; }
 9         for ($i=0; $i < count($ips); $i++){
10             if(!preg_match('^(10│172.16│192.168).', $ips[$i])){
11                 $ip=$ips[$i];
12                 break;
13             }
14         }
15     }
16     return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
17 }

方法二:

function getIp(){
    $ip='未知IP';
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        return is_ip($_SERVER['HTTP_CLIENT_IP'])?$_SERVER['HTTP_CLIENT_IP']:$ip;
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        return is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$ip;
    }else{
        return is_ip($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:$ip;
    }
}
function is_ip($str){
    $ip=explode('.',$str);
    for($i=0;$i<count($ip);$i++){
        if($ip[$i]>255){
            return false;
        }
    }
    return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$str);
}

方法 三:

 1 function get_ip(){
 2     static $realip;
 3     if(isset($_SERVER)){
 4         if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
 5             $realip=$_SERVER['HTTP_X_FORWARDED_FOR'];
 6         }else if(isset($_SERVER['HTTP_CLIENT_IP'])){
 7             $realip=$_SERVER['HTTP_CLIENT_IP'];
 8         }else{
 9             $realip=$_SERVER['REMOTE_ADDR'];
10         }
11     }else{
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');
16         }else{
17             $realip=getenv('REMOTE_ADDR');
18         }
19     }
20     return $realip;
21 }

 

posted @ 2018-04-19 10:23  临点  阅读(197)  评论(0编辑  收藏  举报