如何获得用户'的国家/地区,并转发到URL

How to get user's country and forward to URL?

本文关键字:地区 转发 URL 国家 用户 何获得      更新时间:2023-10-02

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

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

最好使用PHP,但必要时可以使用Javascript。

这可能有助于您获得国家/地区,然后您可以相应地重定向。

<?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中。

<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>

请查看下面的链接。

如何检测访问者';的国家,并将他/她重定向到特定的网站?

也许它会对你有所帮助…:)

您可以使用PECL的geoip_country_by_name()和用户的ip地址来获取他们的国家/地区:

<?php

    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $country = geoip_country_name_by_name($ip);
    if ($country) {
        echo 'This host is located in: ' . $country;
        //header("Location: " . $somelocation);
    }
    ?>