【问题标题】:Redirect country script not working重定向国家脚本不起作用
【发布时间】:2014-03-14 23:45:46
【问题描述】:

我需要一点帮助

首先,我从这里下载了 MaxMind 的 GeoIP.dat 数据库

然后我从这里下载了 geoip.inc

然后我将这两个文件上传到我的页面所在的同一目录。

我编辑了我的 php 页面并在其中编写了这个脚本:

<?php
require_once('geoip.inc');

$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
 $country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);

$my_countries = array('us', 'ca', 'gb', 'fr', 'de', 'nl');
if (!in_array(strtolower($country), $my_countries))
{
header('Location: http://"ALL"TRAFFICURLGOESHERE.whatever');
}
else
{
header('Location: http://"SELECTEDCOUNTRIES"URLGOESHERE.whatever');
}
?>  

而且效果很好!

但是

我想要这样的东西:

  • A 国用户重定向到 W url
  • B 国用户重定向到 X 网址
  • C 国用户重定向到 Y 网址
  • D 国用户重定向到 Z 网址

其余国家/地区用户重定向到我想要的相同 URL。

任何人都可以使用 2-3 个国家/地区示例编辑此 php 代码到不同的 URL,并保留到我想要的其他 URL,以便我可以学习如何向该代码添加更多其他(超过 4 个国家/地区)国家/地区,因为我我真的不擅长 php 或 html。

我也试过这个(下面的代码),但那不起作用

<?php
 require_once('geoip.inc');
$gi = geoip_open('GeoIP.dat', GEOIP_MEMORY_CACHE);
$country = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
$my_countries = 'us';
if (strtolower($country) == $my_countries) {
header('Location: example.us');
}
$my_countriess = 'nz';
if (strtolower($country) == $my_countriess) {
header('Location: example.co.nz);
}
$my_countriesss = 'uk';
if (strtolower($country) == $my_countriesss) {
header('Location: example.co.uk');
}
$my_countriessss = 'ca';
if (strtolower($country) == $my_countriessss) {
header('Location: example.ca');
}
?>

【问题讨论】:

  • 您遇到语法错误,其中缺少一行结尾的单引号:header('Location: example.co.nz);

标签: php redirect geo


【解决方案1】:

我想要这样的东西:国家 A 用户重定向到 W url...而其余国家用户重定向到我想要的相同 URL。

由于您是 PHP 新手,听起来您想使用一系列简单的if 语句?

if ($country === "us"){
    // redirect to US
} else if ($country === "nz"){
    // redirect to nz
} else if ($country === "..."){
    // continue specifically targeting country codes
} else {
    // redirect to everywhere else if none of the above match
}

随着您的了解,您可能需要使用 strtolower() 以便字符串匹配。

【讨论】:

    【解决方案2】:

    您可以为此使用switch ... case

    例子:

    switch ($country) {
         case 'us':
             $location = 'USURL';
             break;
         case 'uk':
             $location = 'UK URL';
             break;
         case ...
         ...
         default:
             $location = 'other countries url';
             break;
    }
    header('Location: $location');
    

    有关switch 声明的更多信息,请参阅http://www.php.net/manual/en/control-structures.switch.php

    编辑: 顺便说一句,在您的第二个代码中缺少分号:

    header('Location: example.co.nz);
    

    应该是

    header('Location: example.co.nz');
    

    【讨论】:

    • 我知道当我开始学习 PHP 时,switchcase 对我来说看起来很可怕。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2014-03-11
    • 2013-11-08
    • 2017-09-20
    • 2012-10-08
    • 2021-01-17
    相关资源
    最近更新 更多