Home  >  Article  >  php教程  >  php 取得真实ip兼容性写法.

php 取得真实ip兼容性写法.

PHP中文网
PHP中文网Original
2016-05-25 17:07:151066browse


function fun_get_ip(){
       static $ip = null;
       if($ip)
         return $ip; // 不需要计算第二次.
       $ip=false;
       if($_SERVER['HTTP_VIA']){
           if(!empty($_SERVER["HTTP_CLIENT_IP"])){
                $ip = $_SERVER["HTTP_CLIENT_IP"];
           }else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
                if ($ip){
                    array_unshift($ips, $ip); $ip = false;
                }
                $ipss = count($ips);
                for ($i = 0; $i < $ipss; $i++){
                     if (!preg_match(&#39;/^(10|172\.16|192\.168)\./&#39;, $ips[$i])){
                               $ip = $ips[$i];
                               break;
                     }
                }
           }
       }else{
            $ip = $_SERVER[&#39;REMOTE_ADDR&#39;];
       }
        
       # 更兼容的获取.
        if(!$ip)
        if(!$ip = getenv("REMOTE_ADDR"))
        if (!$ip = getenv("HTTP_CLIENT_IP"))
        if(!$ip = getenv("HTTP_X_FORWARDED_FOR"))
            $ip = false;
       return $ip;
}

                   

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn