PHP获取访客真实IP
编写程序,并给出注释
// 获取访客真实 if
function getIp()
{
$realip = ”;
$unknown = ‘unknown’;
if (isset($_SERVER)){
if(isset($_SERVER[‘HTTP_X_FORWARDED_FOR’]) && !empty($_SERVER[‘HTTP_X_FORWARDED_FOR’]) && strcasecmp($_SERVER[‘HTTP_X_FORWARDED_FOR’], $unknown)){
//使用透明代理、欺骗性代理的情况
$arr = explode(‘,’, $_SERVER[‘HTTP_X_FORWARDED_FOR’]);
foreach($arr as $ip){
$ip = trim($ip);
if ($ip != ‘unknown’){
$realip = $ip;
break;
}
}
}else if(isset($_SERVER[‘HTTP_CLIENT_IP’]) && !empty($_SERVER[‘HTTP_CLIENT_IP’]) && strcasecmp($_SERVER[‘HTTP_CLIENT_IP’], $unknown)){
//”HTTP_CLIENT_IP”是指用户的客户软件(如浏览器或者代理服务器)向代理服务器发出请求时使用的IP地址
$realip = $_SERVER[‘HTTP_CLIENT_IP’];
}else if(isset($_SERVER[‘REMOTE_ADDR’]) && !empty($_SERVER[‘REMOTE_ADDR’]) && strcasecmp($_SERVER[‘REMOTE_ADDR’], $unknown)){
//正在浏览当前页面用户的IP地址
$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”);
}else if(getenv(‘HTTP_CLIENT_IP’) && strcasecmp(getenv(‘HTTP_CLIENT_IP’), $unknown)){
$realip = getenv(“HTTP_CLIENT_IP”);
}else if(getenv(‘REMOTE_ADDR’) && strcasecmp(getenv(‘REMOTE_ADDR’), $unknown)){
$realip = getenv(“REMOTE_ADDR”);
}else{
$realip = $unknown;
}
}
$realip = preg_match(“/[d.]{7,15}/”, $realip, $matches) ? $matches[0] : $unknown;
return $realip;
}2023年03月18日 23:21