如何获取用户的国家/地区并转发到URL? [英] How to get user's country and forward to URL?

查看:119
本文介绍了如何获取用户的国家/地区并转发到URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取用户的国家/地区并将其转发到基于此的网址?

How can I get the user's country and forward them to a URL based on it?

我特别关注澳大利亚,新西兰,美国,英国和其他。

I am looking specifically at Australia, New Zealand, USA, UK and Other.

最好使用PHP,但如果需要可以使用Javascript。

Preferably with PHP, but can use Javascript if necessary.

推荐答案

这可以帮助你获得国家,然后你可以相应地重定向。

This may help you to get country then you can redirect accordingly.

<?PHP

  function visitor_country()
  {
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    $result  = "Unknown";
    if(filter_var($client, FILTER_VALIDATE_IP))
    {
       $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
      $ip = $forward;
    }
    else
    {
      $ip = $remote;
    }

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

    if($ip_data && $ip_data->geoplugin_countryName != null)
    {
       $result = $ip_data->geoplugin_countryName;
    }

    return $result;
}

echo visitor_country(); // Output Coutry name [Ex: United States]

?>

或在Javascript中。

OR in Javascript.

<html>
<head>
  <script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
</head>
<body>
  <script language="Javascript"> 
document.write("Welcome to our visitors from "+geoplugin_city()+", "+geoplugin_countryName()); 
// window.location = "http://www.yoururl.com";  /* you can forward user to url using this line of code according to your conditions
  </script>
</body>
</html>

这篇关于如何获取用户的国家/地区并转发到URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆