试图将我的网站限制在特定国家/地区

Trying to restrict my site to a specific country

我试图使用我找到的这段代码将我的网站限制在特定国家/地区,但我似乎无法让它正常工作。

我的问题是即使 $country 与数组

中的内容不同,它也总是返回 true

我知道通过 GeoIP 限制我的网站并不是万无一失的,但它会让我的问题减少人们试图从不同国家注册,因为我们举办的活动仅限于一个小地理区域。

我已经检查过我的问题是否与缓存有关并且我的网站没有缓存输出。

我也知道 $country 和我试过的一样有效 echo ($country);

这是代码

$allowed_countries = array("CA", "US");

$country = file_get_contents("http://ipinfo.io/{$_SERVER['REMOTE_ADDR']}/country");


if (in_array($country, $allowed_countries)) {

  header('Location: http://www.letsgetsocialclub.com/site');

} else {

echo "Sorry The Let's Get Social Club is not available in your country";

}

您在请求中使用的 url returns 末尾带有 \n 的国家/地区代码,因此您尝试检查的值不在您的数组中。
您可以使用 trim 函数删除字符串开头和结尾的所有空格以清除它:

$country = trim(file_get_contents("http://ipinfo.io/{$_SERVER['REMOTE_ADDR']}/country"));

为确保国家/地区代码没有多余字符,请将您的代码替换为以下内容:

$allowed_countries = array("CA", "US");

$country = preg_replace('/[^A-Z]/', '', file_get_contents("http://ipinfo.io/{$_SERVER['REMOTE_ADDR']}/country"));


if (in_array($country, $allowed_countries)) {

  header('Location: http://www.letsgetsocialclub.com/site');

} else {

echo "Sorry The Let's Get Social Club is not available in your country";

}