个性化阅读
专注于IT技术分析

如何使用请求ip免费检测php或javascript中访客的国家

点击下载

有许多服务不是免费的, 它们为开发人员提供了一个简单的API, 可以从服务器请求中检索国家, 大洲和其他地理数据。但是, 有些开发人员不愿意为服务付费, 因为你只是在测试, 没有钱或任何其他原因, 因此不愿意为该服务付费。 geoplugin.net页面提供了免费的api, 以检索向我们的服务器发出请求的用户所在的国家/地区。

我们需要使用get参数向geoplugin.net/json.gp发出请求, 该参数必须是请求的IP。

我们可以免费检索一些重要信息, 该对象中提供以下密钥:

  • geoplugin_request:包含我们刚刚发送的IP get参数中的IP。
  • geoplugin_status:请求的http状态代码
  • geoplugin_city:请求IP的城市(如果有)
  • geoplugin_countryCode:2个字符的国家/地区代码(美国, 德国, 俄罗斯)
  • geoplugin_countryName
  • geoplugin_continentCode
  • geoplugin_currencyCode:国家处理的货币(欧元, 美元)
  • geoplugin_regionCode
  • geoplugin_regionName
  • geoplugin_areaCode
  • geoplugin_currencySymbol:货币的HTML符号。

使用php, 事情真的很简单, 我们需要使用php本机变量$ SERVER检索请求的IP, 该变量包含有关请求的信息。然后, 我们需要检索提到的网页的信息(实际上将返回JSON响应, 但是我们需要使用json_decode函数转换为数组)。

$ip = $_SERVER['REMOTE_ADDR']; // This will contain the ip of the request

// You can use a more sophisticated method to retrieve the content of a webpage with php using a library or something
// We will retrieve quickly with the file_get_contents
$dataArray = json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));

var_dump($dataArray);

// outputs something like (obviously with the data of your IP) :

// geoplugin_countryCode => "DE", // geoplugin_countryName => "Germany"
// geoplugin_continentCode => "EU"

echo "Hello visitor from: ".$dataArray["geoplugin_countryName"];

使用Javascript有点复杂。首先, 我们需要以某种方式检索用户的IP, 问题是用php检索IP并非那么容易, 你需要一种或另一种方式进行服务器调用以检索IP。如果由于没有服务器等原因而无法使用PHP, 请在StackOverflow中查看此问题, 可以通过添加使用JSONP(回调)的脚本来检索ip。

然后, 我们需要对上述网址进行请求以获取ip的国家/地区, 但是如果我们仅对网址进行请求, 就会遇到以下问题:

XMLHttpRequest cannot load http://www.geoplugin.net/json.gp?ip=my.ip.number  No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mywebsiterequestdomain' is therefore not allowed access.

此问题是由于CORS限制所致, 你无法对不是你自己的服务器执行ajax请求。要解决此问题, 我们需要跳过此限制, 我们将使用cors-anywhere网站来避免这种情况。然后我们的请求将如下所示:

var ip = "the ip number, retrieved of some way by a server";

// the request will be to http://www.geoplugin.net/json.gp?ip=my.ip.number but we need to avoid the cors issue, and we use cors-anywhere api.

$.getJSON("https://cors-anywhere.herokuapp.com/http://www.geoplugin.net/json.gp?ip="+ip, function(response){
    console.log(response);
    // output an object which contains the information.
    alert("Hello visitor from "+ response.geoplugin_countryName);

});

注意:如果可以并且有服务器可以发出请求, 请使用PHP方式, 因为它既简单又简洁, 因为我们不需要在任何地方使用cors。

下面的小提琴允许你使用带有javascript和jQuery.getJSON函数的简单表单从ip检索国家/地区。转到结果标签, 然后自己尝试。

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何使用请求ip免费检测php或javascript中访客的国家

评论 抢沙发

评论前必须登录!