首页 > 解决方案 > 在 IP2Location 重定向上设置 URL 相同页面

问题描述

我将使用按国家/地区重定向访问者,我使用IP2LOCATION

这是我的代码:

require_once('vendor/geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
$var_country_code = $geoplugin->countryCode;
if ($var_country_code == "IN") {
    header('Location: index.php?lang=in');
}
if ($var_country_code == "MY") {
    header('Location: index.php?lang=my');
}

我在 index.php 文件的头部添加了上面的代码,问题是页面不断刷新。

例如,index.php 将正确重定向到 index.php?lang=in,但它会不断刷新......

我试过退出;休息; 元刷新,session_start();和其他方法。我需要添加会话开始,注册会话并设置cookie,只有一次在访问者国家重定向到语言后,用户将能够在此之后更改语言。

这是我的语言代码:

session_start();
header('Cache-control: private'); 
if(isSet($_GET['lang']))
{
    $lang = $_GET['lang'];
    // register the session and set the cookie
    $_SESSION['lang'] = $lang;
    setcookie("lang", $lang, time() + (3600 * 24 * 30));
}
else if(isSet($_SESSION['lang']))
{
    $lang = $_SESSION['lang'];
}
else if(isSet($_COOKIE['lang']))
{
    $lang = $_COOKIE['lang'];
}
else
{
    $lang = 'en';
}

如何解决这个问题?

提前致谢

标签: phpsession-cookiessetcookieip2location

解决方案


将您的位置存储在会话变量中,如果已设置,则不需要再次刷新位置会话,从而中断重定向循环。您不需要语言代码。

session_start();
require_once('vendor/geoplugin.class.php');

if(!$_SESSION['location']){

    $geoplugin = new geoPlugin();
    $geoplugin->locate();
    $var_country_code = $geoplugin->countryCode;

    $_SESSION['location'] = $var_country_code;

    if ($var_country_code == "IN") {

           header('Location: index.php?lang=in');
    }
    if ($var_country_code == "MY") {

            header('Location: index.php?lang=my');
    }

}

推荐阅读