第一种方法,还算靠谱:
function get_real_ip(){
$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']);
}
注意:上面正则会在5.3以后版本出错,需使用新方法 if(!preg_match('/^(10│172.16│192.168).*$/i', $ips[$i])){
第二种方法:
function get_real_ip(){
static $realip;
if(isset($_SERVER)){
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$realip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else if(isset($_SERVER['HTTP_CLIENT_IP'])){
$realip=$_SERVER['HTTP_CLIENT_IP'];
}else{
$realip=$_SERVER['REMOTE_ADDR'];
}
}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');
}
}
return $realip;
}
第三种方法,摘自DISCUZ,应该还不错吧!
function getIp(){
$ip='未知IP';
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
return is_ip($_SERVER['HTTP_CLIENT_IP'])?$_SERVER['HTTP_CLIENT_IP']:$ip;
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
return is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$ip;
}else{
return is_ip($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:$ip;
}
}
function is_ip($str){
$ip=explode('.',$str);
for($i=0;$i
if($ip[$i]>255){
return false;
}
}
return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$str);
}
如果觉得《php获取ip所有方式 php获取用户(客户端)真实IP地址的三种方法》对你有帮助,请点赞、收藏,并留下你的观点哦!