通常情况下,$_SERVER["REMOTE_ADDR"]就已经代表了客户IP,但有时候也不可行,例如服务器端(尤其是虚拟主机和代理服务器 的情况)设置了缓冲区等情况,如果不另找办法,则以上方法返回的客户IP总是127.0.0.1。以下是最全最真实的取客户IP的方法。
// 取得客户IP
function get_client_ip()
{
global $_SERVER;
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_CLIENT_IP"]))
{
$realip = $_SERVER["HTTP_CLIENT_IP"];
}
else
{
$realip = $_SERVER["REMOTE_ADDR"];
}
return $realip;
}
或者:
function get_client_ip()
{
if (isset($_SERVER['HTTP_CLIENT_IP']) and !empty($_SERVER['HTTP_CLIENT_IP']))
{
return $_SERVER['HTTP_CLIENT_IP'];
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
return strtok($_SERVER['HTTP_X_FORWARDED_FOR'], ',');
}
if (isset($_SERVER['HTTP_PROXY_USER']) and !empty($_SERVER['HTTP_PROXY_USER']))
{
return $_SERVER['HTTP_PROXY_USER'];
}
if (isset($_SERVER['REMOTE_ADDR']) and !empty($_SERVER['REMOTE_ADDR']))
{
return $_SERVER['REMOTE_ADDR'];
}
else
{
return "0.0.0.0";
}
}
表示看不懂
,但有时候也不可行,例如服务器端 (尤其是虚拟主,但有时候也不可行,例如服 务器端(尤其是虚拟主