Home >Backend Development >PHP Tutorial > php怎么获取真实IP

php怎么获取真实IP

WBOY
WBOYOriginal
2016-06-13 12:53:091044browse

php如何获取真实IP
试了网上很多代码都不行,但是ip138每次都能显示我的真实ip。特求各位大侠支招。

比如我用一般的php获得的我的ip地址是:60.55.8.229 - 浙江宁波

但是ip38.com获取的我的IP地址是:[42.196.192.67] 来自:上海市 长城宽带

ip138才是正确的。

我在医院里测试也是这样,自己的php代码获取的IP是浙江杭州

但是ip138却能获得我的真实ip,上海交通大学

我现在用的PHP代码如下:

function GetIP(){ <br />
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) <br />
$ip = getenv("HTTP_CLIENT_IP"); <br />
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) <br />
$ip = getenv("HTTP_X_FORWARDED_FOR"); <br />
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) <br />
$ip = getenv("REMOTE_ADDR"); <br />
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) <br />
$ip = $_SERVER['REMOTE_ADDR']; <br />
else <br />
$ip = "unknown"; <br />
return($ip); <br />
} <br />
echo GetIP();


------解决方案--------------------
呃是我的方法:
Function curIp(){<br />
		$ip='';<br />
		IF(Getenv('HTTP_CLIENT_IP') And StrCaseCmp(Getenv('HTTP_CLIENT_IP'),'unknown')){<br />
			$ip=Getenv('HTTP_CLIENT_IP');<br />
		}ElseIF(Getenv('HTTP_X_FORWARDED_FOR') And StrCaseCmp(Getenv('HTTP_X_FORWARDED_FOR'),'unknown')){<br />
			$ip=Getenv('HTTP_X_FORWARDED_FOR');<br />
		}ElseIF(Getenv('REMOTE_ADDR')And StrCaseCmp(Getenv('REMOTE_ADDR'),'unknown')){<br />
			$ip=Getenv('REMOTE_ADDR');<br />
		}ElseIF(isset($_SERVER['REMOTE_ADDR']) And $_SERVER['REMOTE_ADDR'] And StrCaseCmp($_SERVER['REMOTE_ADDR'],'unknown')){<br />
			$ip=$_SERVER['REMOTE_ADDR'];<br />
		}Else{<br />
			$ip='127.0.0.1';<br />
		}<br />
		Return $ip;<br />
	}

------解决方案--------------------
function real_ip()
{
static $realip = NULL;

if ($realip !== NULL)
{
return $realip;
}

if (isset($_SERVER))
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

/* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
foreach ($arr AS $ip)
{
$ip = trim($ip);

if ($ip != 'unknown')
{
$realip = $ip;

break;
}
}
}
elseif (isset($_SERVER['HTTP_CLIENT_IP']))
{
$realip = $_SERVER['HTTP_CLIENT_IP'];
}
else
{
if (isset($_SERVER['REMOTE_ADDR']))
{
$realip = $_SERVER['REMOTE_ADDR'];
}
else
{
$realip = '0.0.0.0';
}
}
}
else
{
if (getenv('HTTP_X_FORWARDED_FOR'))
{
$realip = getenv('HTTP_X_FORWARDED_FOR');
}
elseif (getenv('HTTP_CLIENT_IP'))
{
$realip = getenv('HTTP_CLIENT_IP');
}
else
{
$realip = getenv('REMOTE_ADDR');
}
}
$onlineip = null;
preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

return $realip;
}
------解决方案--------------------
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