×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: PHP
Posted by: Jing Tai Piao
Added: Mar 17, 2013 11:19 PM
Modified: Nov 15, 2013 3:00 AM
Views: 38
Tags: no tags
  1. function fun_get_ip(){
  2.        static $ip = null;
  3.        if($ip)
  4.          return $ip; // 不需要计算第二次.
  5.        $ip=false;
  6.        if(isset($_SERVER['HTTP_VIA'])){
  7.            if(!empty($_SERVER["HTTP_CLIENT_IP"])){
  8.                 $ip = $_SERVER["HTTP_CLIENT_IP"];
  9.            }else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
  10.                 $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
  11.                 if ($ip){
  12.                     array_unshift($ips, $ip); $ip = false;
  13.                 }
  14.                 $ipss = count($ips);
  15.                 for ($i = 0; $i < $ipss; $i++){
  16.                      if (!preg_match('/^(10|172\.16|192\.168)\./', $ips[$i])){
  17.                                $ip = $ips[$i];
  18.                                break;
  19.                      }
  20.                 }
  21.            }
  22.        }else{
  23.             $ip = $_SERVER['REMOTE_ADDR'];
  24.        }
  25.        
  26.        # 更兼容的获取.
  27.        if(!$ip)
  28.         if(!$ip = getenv("REMOTE_ADDR"))
  29.         if (!$ip = getenv("HTTP_CLIENT_IP"))
  30.         if(!$ip = getenv("HTTP_X_FORWARDED_FOR"))
  31.             $ip = false;
  32.        return $ip;
  33. }

2 comments

Greg Milby 3 years ago
i got an error - just wrapping the HTTP_VIA in an isset( seems to have cleared it up
===>> if(isset($_SERVER['HTTP_VIA'])){

Thank you for sharing your snippet - it's better than what i had been using.
Jing Tai Piao 3 years ago
Thanks for your comments.

Write a comment