Home > php教程 > PHP源码 > body text

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

PHP中文网
Release: 2016-05-25 17:07:15
Original
1065 people have browsed it


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;
}
Copy after login

                   

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!