【问题标题】:Get user Country Code by IP via php function通过 php 函数通过 IP 获取用户国家代码
【发布时间】:2021-04-29 14:21:14
【问题描述】:

我有一个来自现有系统的代码 sn-p,它从过时的数据库表中提取用户的 2 位国家代码。通常我会定期更新表格,但老实说,我很讨厌这样做。我想做的是在每次用户登录时让这更像是一次实时拉动。这是现有代码

    public static function geoip_country_code_by_name($ip)
    {
        if ($_SERVER['HTTP_CF_IPCOUNTRY']) {
            return $_SERVER['HTTP_CF_IPCOUNTRY'];
        }
        $sql = "SELECT country  FROM ip2country WHERE ip < INET_ATON('$ip') ORDER BY ip DESC LIMIT 0,1";
        $res = DB::selectOneBySQL($sql);
        return $res->country;
    }

我正在寻找有关如何最好地完成此任务的建议。

【问题讨论】:

    标签: php geolocation country-codes


    【解决方案1】:

    我决定使用这个解决方案。如果需要,它还允许我在未来获取更多信息。我最终可能会使用此 API 或其他 API 转向付费服务,但现在这解决了我的问题

             public static function geoip_country_code_by_name($ip)
            {
                    if ($_SERVER['HTTP_CF_IPCOUNTRY']) {
                        return $_SERVER['HTTP_CF_IPCOUNTRY'];
                    }
               $iptolocation = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
               $creatorlocation = $iptolocation->geoplugin_countryCode;
               return $creatorlocation;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 2013-04-27
      相关资源
      最近更新 更多