点击链接更改语言

3

我有一些链接,例如:

<a href="index.php?lang=en"><img src="images/uk.png" style="height:20px"/></a>

在index.php中包含了一个页面,其中包括了included标签。
<?php
session_start();
header('Cache-control: private'); // IE 6 FIX

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';
}

switch ($lang) {
  case 'en':
  $lang_file = 'lang.en.php';
  break;

  case 'gr':
  $lang_file = 'lang.gr.php';
  break;

  default:
  $lang_file = 'lang.en.php';

}

include_once 'languages/'.$lang_file;
?>

它将URL更改为index.php?lang=gr,读取参数LANG并根据该参数翻译页面。

如何在不将参数传递到URL的情况下更改我的代码?我的意思是,我希望用户在页面刷新时仍然停留在同一页面并更改语言。

2个回答

1
以下是它的内容;
        <input type="submit" value="" class=<?php if( $_SESSION['lang']  == "tr" ) { echo "submittr";  } else { echo "submiten";} ?>>

在这种情况下,您将更改类的类型。

0

有几种方法可以做到这一点,其中之一是使用表单并将“提交”按钮设置为您的图像。该表单将使用POST方法,该方法不会在URL中包含变量。GET请求将添加?lang=en

<div id="buttons">
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
        <input type="hidden" name="lang" value="en">
        <button type="submit">
            <img src="images/uk.png" style="height:20px"/>
        </button>
    </form>
</div>

修改您的代码以使用 $_POST 变量:

if(isSet($_POST['lang']))
{
$lang = $_POST['lang'];

你为什么要通过URL/GET传递所有变量呢?你可能想把需要的变量存储在SESSION或COOKIE中。 - immulatin
@AndreyPopov 这是另一篇关于该主题的相当不错的文章:http://www.wisdombay.com/articles/basic%20guide%20to%20mod_rewrite.htm - Funk Forty Niner
我可以在URL中显示所有其他变量,因为这使用户能够直接获取类别、对象等的链接...但是语言存储在Cookie中,所以我不想在URL中显示它...现在唯一的问题是如何在按钮单击时将用户重定向回他正在查看的页面:localhost:8888/index.php?cat=2,因为现在他被重定向到localhost:8888/index.php...也许我可以将$_SERVER['PHP_SELF']更改为其他内容? - Andrey Popov
是的,每次我尝试刷新页面时都会出现错误...它会询问我是否要提交表单。 - Andrey Popov
你需要使用ajax/jquery/javascript等客户端技术,如果你不想在URL中显示GET参数或者不想在刷新页面时提交表单。GET和POST是PHP的两个选项,但都不能满足你的需求。 - immulatin
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接