此ip获得函数的优点是apahce2运行时不报错。
function getRealIp()
{
$ip=false;
if(!empty($_SERVER["HTTP_CLIENT_IP"])){
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
for ($i = 0; $i < count($ips); $i++) {
if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
$ip = $ips[$i];
break;
}
}
}
return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
echo getRealIp();
下面的代码页能获得ip地址,但apache2运行报错
PHP Notice: Use of undefined constant HTTP_X_FORWARDED_FOR - assumed 'HTTP_X_FORWARDED_FOR'
function getip()
{
if (isset($_SERVER))
{
if (isset($_SERVER[HTTP_X_FORWARDED_FOR]) && strcasecmp($_SERVER[HTTP_X_FORWARDED_FOR], "unknown"))//代理
{
$realip = $_SERVER[HTTP_X_FORWARDED_FOR];
}
elseif(isset($_SERVER[HTTP_CLIENT_IP]) && strcasecmp($_SERVER[HTTP_CLIENT_IP], "unknown"))
{
$realip = $_SERVER[HTTP_CLIENT_IP];
}
elseif(isset($_SERVER[REMOTE_ADDR]) && strcasecmp($_SERVER[REMOTE_ADDR], "unknown"))
{
$realip = $_SERVER[REMOTE_ADDR];
}
else
{
$realip = 'unknown';
}
}
else
{
if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
{
$realip = getenv("HTTP_X_FORWARDED_FOR");
}
elseif(getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
{
$realip = getenv("HTTP_CLIENT_IP");
}
elseif(getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
{
$realip = getenv("REMOTE_ADDR");
}
else
{
$realip = 'unknown';
}
}
return $realip;
}