简体   繁体   English

如何在php中获取真实的客户端IP或地理位置?

[英]How to get real client ip or geolocation in php?

I have a user registration system on my site. 我的网站上有一个用户注册系统。 I am using xml ip api of ip-api.com to detect the location of users. 我正在使用ip-api.com的xml ip api来检测用户的位置。 My problem is that the php script I am using returns proxy or wrong ip address of users ,and that is why I they can not set correct location in their profile. 我的问题是我使用的php脚本返回用户的代理或错误的IP地址,这就是为什么我不能在他们的配置文件中设置正确的位置。

I use the following conditional statement to get ip address : 我使用以下条件语句来获取IP地址:

   $ip=$_SERVER["REMOTE_ADDR"];
 if(empty($ip))
 {$ip=

$_SERVER["HTTP_X_FORWARDED_FOR"];} $ _SERVER [“ HTTP_X_FORWARDED_FOR”];}

It returns wrong ip address for some users. 它为某些用户返回了错误的IP地址。

Is there any other way to get real ip or geolocation in php? 还有其他方法可以在php中获得真实的IP或地理位置吗?

You can see this topic : How to get Real IP from Visitor? 您可以看到以下主题: 如何从Visitor获取真实IP?

function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    return $ip;
}
$user_ip = getUserIP();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM