获取客户真实ip
- 方法
function get_client_ip(){
$headers = array('HTTP_X_REAL_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR');
foreach ($headers as $h){
$ip = $_SERVER[$h];
// 有些ip可能隐匿,即为unknown
if ( isset($ip) && strcasecmp($ip, 'unknown') ){
break;
}
}
if( $ip ){
// 可能通过多个代理,其中第一个为真实ip地址
list($ip) = explode(', ', $ip, 2);
}
/* 如果是服务器自身访问,获取服务器的ip地址(该地址可能是局域网ip)
if ('127.0.0.1' == $ip){
$ip = $_SERVER['SERVER_ADDR'];
}
*/
return $ip;
}
- 方法
function getRealIp() {
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$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'])) {
$realip = $_SERVER['HTTP_CLIENT_IP'];
} else if (isset($_SERVER['REMOTE_ADDR'])) {
$realip = $_SERVER['REMOTE_ADDR'];
} else {
$realip = '0.0.0.0';
}
} else if (getenv('HTTP_X_FORWARDED_FOR')) {
$realip = getenv('HTTP_X_FORWARDED_FOR');
} else if (getenv('HTTP_CLIENT_IP')) {
$realip = getenv('HTTP_CLIENT_IP');
} else {
$realip = getenv('REMOTE_ADDR');
}
preg_match('/[\d\.]{7,15}/', $realip, $onlineip);
$realip = (!empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0');
return $realip;
}
参考链接