php - 在 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';
}
如何解决这个问题?
提前致谢
解决方案
将您的位置存储在会话变量中,如果已设置,则不需要再次刷新位置会话,从而中断重定向循环。您不需要语言代码。
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');
}
}
推荐阅读
- regex - 如何制作 ANTLR 双正则表达式?
- reactjs - 在 React 中开发时,是否可以在 chrome 调试器中调试 JSX 变量?
- html - 是否可以保证表格标题中的垂直文本?
- utf-8 - Flutter阿拉伯语字符串包含Html代码UTF8解码问题
- javascript - 如果不能使用 JS 函数,还有什么理由给它起名字?
- javascript - 如何使用 javascript 和 html 创建搜索栏
- javascript - 将字符串评估为 EJS 中的变量
- android - 在 Android 中关闭应用程序时使用 AppCenter 推送通知
- python - 如何使变量等于多个字符串?
- pip - 我在 Mac 上安装了 pip 和 conda。现在管理python包的最佳方法是什么?