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(){
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return($ip);
}
echo GetIP();
------解决方案--------------------這是我的方法:
Function curIp(){
$ip='';
IF(Getenv('HTTP_CLIENT_IP') And StrCaseCmp(Getenv('HTTP_CLIENT_IP'),'unknown')){
$ip=Getenv('HTTP_CLIENT_IP');
}ElseIF(Getenv('HTTP_X_FORWARDED_FOR') And StrCaseCmp(Getenv('HTTP_X_FORWARDED_FOR'),'unknown')){
$ip=Getenv('HTTP_X_FORWARDED_FOR');
}ElseIF(Getenv('REMOTE_ADDR')And StrCaseCmp(Getenv('REMOTE_ADDR'),'unknown')){
$ip=Getenv('REMOTE_ADDR');
}ElseIF(isset($_SERVER['REMOTE_ADDR']) And $_SERVER['REMOTE_ADDR'] And StrCaseCmp($_SERVER['REMOTE_ADDR'],'unknown')){
$ip=$_SERVER['REMOTE_ADDR'];
}Else{
$ip='127.0.0.1';
}
Return $ip;
}
------解决方案--------------------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;
}
------解决方案------------------