cdn或反向代理后获取用户真实IP的函数代码PHP版

发布时间:2020-11-18编辑:脚本学堂
做了cdn或反向代理后,如何获取用户真实IP呢?本文借用discuz中的一段代码,稍作修改,可以获取一级代理、二级代理下的用户真实IP地址,供大家学习参考。

以下代码参考自discuz中的代码。
(discuz修改include/common.inc.php)
 

复制代码 代码示例:

<?php
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')) {
$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')) {
$testip = explode('.', getenv('HTTP_X_FORWARDED_FOR'));

if ($testip[0]=='192′ && $testip[1]=='168′) {
$onlineip = getenv('REMOTE_ADDR');
}
elseif($testip[0]=='10′) {
$onlineip = getenv('REMOTE_ADDR');
}
else {
$onlineip = getenv('HTTP_X_FORWARDED_FOR');
}

//gamesir hack end} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'),'unknown')) {
$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'],'unknown')) {
//by Johnny
$tmp_ip = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
$tmp_ip1 = explode(',',$tmp_ip[0]);
if ($tmp_ip1[0] =='192′ && $tmp_ip1[1] =='168′) {
$onlineip = getenv('REMOTE_ADDR');
}else if($tmp_ip1[0]=='10′) {
$onlineip = getenv('REMOTE_ADDR');
}
else{
$onlineip = $tmp_ip[0];
}
unset($tmp_ip);unset($tmp_ip1);
}
?>

替换这段代码:
 

复制代码 代码示例:
<?php
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')) {
$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')) {
$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'),'unknown')) {
$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'],'unknown')) {
$onlineip = $_SERVER['REMOTE_ADDR'];
}
?>