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

时间:2015-07-19 22:57:07

标签: php geoip

我正在尝试使用我找到的代码将我的网站限制到特定国家/地区,但我似乎无法让它运行。

我的问题是,即使$country与数组中的内容不同,它也始终返回

我知道通过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";

}

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

要确保国家/地区代码中没有多余字符,请使用以下代码替换您的代码:

$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";

}
相关问题