获取用户IP地址的功能[重复]
Posted
技术标签:
【中文标题】获取用户IP地址的功能[重复]【英文标题】:Function to get user ip address [duplicate] 【发布时间】:2011-10-06 18:30:30 【问题描述】:可能重复:What is the most accurate way to retrieve a user's correct IP address in php?
php中是否有更好的函数来获取用户IP地址? 这是我目前使用的
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);
【问题讨论】:
“更好”在什么意义上?您的代码在哪些方面需要改进? 你从哪里得到这个函数的?你为什么用它?它应该有什么坏处?你遇到什么问题了吗? @Jon - 首先是缩进。 ;-) 【参考方案1】:改编自this answer:
function GetIP()
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
if (array_key_exists($key, $_SERVER) === true)
foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip)
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
return $ip;
检查 IP(按顺序):
HTTP_CLIENT_IP
HTTP_X_FORWARDED_FOR
HTTP_X_FORWARDED
HTTP_X_CLUSTER_CLIENT_IP
HTTP_FORWARDED_FOR
HTTP_FORWARDED
REMOTE_ADDR
请记住,您唯一可以信任的 IP 地址是来自 $_SERVER['REMOTE_ADDR']
的 IP 地址。
【讨论】:
那为什么最后检查REMOTE_ADDR
?
@Anther:当用户不在代理后面时。
太棒了!它运作良好:) 谢谢
返回值的数据类型是什么?
获取 IP 地址的非常好的方法,但是我做了一些更改,我在开发环境中工作,我的 IP 地址是 IP V6 ::1(等于 127.0.0.1).. 它是没有传入这个函数..所以我在foreach循环之后添加了以下几行.. if ( isset( $_SERVER['REMOTE_ADDR'] ) ) return $_SERVER['REMOTE_ADDR']; 返回 '';【参考方案2】:
嗯,您的函数应该按预期运行,但这里有一些建议:
// lowercase first letter of functions. It is more standard for PHP
function getIP()
// populate a local variable to avoid extra function calls.
// NOTE: use of getenv is not as common as use of $_SERVER.
// because of this use of $_SERVER is recommended, but
// for consistency, I'll use getenv below
$tmp = getenv("HTTP_CLIENT_IP");
// you DON'T want the HTTP_CLIENT_ID to equal unknown. That said, I don't
// believe it ever will (same for all below)
if ( $tmp && !strcasecmp( $tmp, "unknown"))
return $tmp;
$tmp = getenv("HTTP_X_FORWARDED_FOR");
if( $tmp && !strcasecmp( $tmp, "unknown"))
return $tmp;
// no sense in testing SERVER after this.
// $_SERVER[ 'REMOTE_ADDR' ] == gentenv( 'REMOTE_ADDR' );
$tmp = getenv("REMOTE_ADDR");
if($tmp && !strcasecmp($tmp, "unknown"))
return $tmp;
return("unknown");
【讨论】:
忘记了;返回后$tmp以上是关于获取用户IP地址的功能[重复]的主要内容,如果未能解决你的问题,请参考以下文章