1 <?php 2 $user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"]; 3 $user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"]; 4 5 echo $user_IP; 6 ?>
【PHP获取访问者IP】的三种方法以及详解
Q:三个IP地址的获取有什么区别?
$_SERVER['REMOTE_ADDR']; $_SERVER['HTTP_CLIENT_IP'];
$_SERVER['HTTP_X_FORWARDED_FOR'];
A:区别如下 $_SERVER['REMOTE_ADDR']; //访问端(有可能是用户,有可能是代理的)IP $_SERVER['HTTP_CLIENT_IP']; //代理端的(有可能存在,可伪造) $_SERVER['HTTP_X_FORWARDED_FOR']; //用户是在哪个IP使用的代理(有可能存在,也可以伪造)
$_SERVER['REMOTE_ADDR']; $_SERVER['HTTP_CLIENT_IP'];
$_SERVER['HTTP_X_FORWARDED_FOR'];
A:区别如下 $_SERVER['REMOTE_ADDR']; //访问端(有可能是用户,有可能是代理的)IP $_SERVER['HTTP_CLIENT_IP']; //代理端的(有可能存在,可伪造) $_SERVER['HTTP_X_FORWARDED_FOR']; //用户是在哪个IP使用的代理(有可能存在,也可以伪造)
方法一:$_SERVER['HTTP_X_FORWARDED_FOR']来获取相应的地址
1 function get_onlineip() { 2 $onlineip = ''; 3 if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) { 4 $onlineip = getenv('HTTP_CLIENT_IP'); 5 } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) { 6 $onlineip = getenv('HTTP_X_FORWARDED_FOR'); 7 } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) { 8 $onlineip = getenv('REMOTE_ADDR'); 9 } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) { 10 $onlineip = $_SERVER['REMOTE_ADDR']; 11 } 12 return $onlineip; 13 }
方法二:利用curl依靠第三方来获取,如http://www.ip138.com/ip2city.asp
1 function get_onlineip() { 2 $ch = curl_init('http://www.ip138.com/ip2city.asp'); 3 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 4 $a = curl_exec($ch); 5 preg_match('/[(.*)]/', $a, $ip); 6 return $ip[1]; 7 }