【问题标题】:Detect two-letter continent code by IP通过IP检测两个字母的大陆代码
【发布时间】:2016-07-18 10:01:05
【问题描述】:

上下文:

我想检测我的用户的两个字母的大陆代码,以允许我有条件地显示美国或更通用的电话号码。

例如如果大陆代码是北美或南美,则显示北美电话号码。否则,显示一般国际电话号码。

我尝试过的:

  1. A similar question on Stack Overflow 是使用轻量级函数解决的,但在我的情况下,该函数没有输出任何内容(即空白)。
  2. PHP 手册列出了 GEOIP 扩展的 geoip_continent_code_by_name 函数,但安装此扩展似乎有点过头了,此外,我对 WHM/cPanel 的命令行安装完全不熟悉。

我的问题:

有没有更简单、更轻量级的IP检测两字母大陆码的方法?

【问题讨论】:

  • 你可以看看这个函数:php.net/manual/fr/function.geoip-continent-code-by-name.php。您需要安装 PECL Geoip。
  • 在尝试 1 中,您检查了错误日志吗?空白输出可能是由错误引起的...或者您可以尝试在 IP 上运行 whois
  • @chris85 唯一的错误与尝试 2 相关(致命错误,调用未定义函数)。
  • 函数调用的第一个值应该是IP,你改了吗?在本地测试我做了$ipinfo = ip_info('50.203.165.214'); echo $ipinfo['country_code'];,它对我有用。
  • 那些echos都是没用的。 Visitor 需要是 IP,$_SERVER['REMOTE_ADDR']..或print_r($ipinfo);

标签: php geoip


【解决方案1】:

您可以使用 MaxMind 的官方 API https://maxmind.github.io/GeoIP2-php/

代码示例

<?php 

require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;

// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader('GeoLite2-Country.mmdb');

// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $reader->country('128.101.101.101');

echo ($record->continent->code);

【讨论】:

【解决方案2】:

你可以使用这个功能:

function get_continent_by_ip($ip = false) {
    $code = false;

    if (!$ip) {
        $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;
        }
    }

    $response = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip={$ip}"));    

    if ($response && isset($response->geoplugin_continentCode)) {
        $code = $response->geoplugin_continentCode;
    }

    return $code;
}

检测用户IP并返回大陆代码

【讨论】:

  • 根据我之前的尝试,结果是空白的。没有记录错误。
  • 可能没有检测到你的ip。您可以使用google.com的IP测试功能:get_continent_by_ip('8.8.8.8');
  • 我的网站和本地空白:pastebin.com/bzVcBT38 即两个独立的环境。
  • 不正确。试试:print get_continent_by_ip('8.8.8.8');$code = get_continent_by_ip('8.8.8.8'); print $code;
  • 本地,结果为“NA”。在我的网站上,结果仍然是空白的。再次重申,我担心 WordPress 可能会限制我网站的输出。这在本地不是问题,因为我的 PHP 文档不在 WordPress 目录中。这是我可以尝试解释行为差异的唯一有根据的猜测。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
相关资源
最近更新 更多