doujing1156 2013-04-16 18:39
浏览 46
已采纳

当我尝试$ _GET时,在URL中设置参数的链接不能按预期工作

I have this PHP code that sets a cookie when the ?setLang parameter is in the URL

if (isSet($_GET["setLang"])) {
    setcookie("lang",$_GET["setLang"]);
}

if (!isSet($_COOKIE["lang"])) {
    //negociate language and set locale
}else{
    //set locale to cookie
}

//translate with gettex

When I go to website.com/?setLand=en it works exactly as expected.

The problem is when I link to the URL in this form from website.com:

<a href="?setLang=en">en</a>

When I click it, through the link (and not go directly) the gettext translation doesn't work, but otherwise, it works as expected.

My first though was that I had to force some kind of refresh, so I did:

<a href="?setLang=en" onClick="window.location.reload( true );">en</a>

But it doesn't work.

I inspected the code and the cookie is in fact set when you click the link so it confuses me even further.



The full code just in case is the following:

<?php
if (isSet($_GET["setLang"])) {
    setcookie("lang",$_GET["setLang"]);
}
if (!isSet($_COOKIE["lang"])) {
    $langs = array(
        'en-US',// default
        'fr',
        'fr-FR',
        'de',
        'de-DE',
        'de-AT',
        'de-CH',
    );
    $locale = substr(http_negotiate_language($langs), 0, 2);
}else{
    $locale = $_COOKIE["lang"];
}

//if (isSet($_GET["locale"])) $locale = $_GET["locale"];
if($locale == "en") 
    $locale = "en_US.utf8";
if($locale == "de") 
    $locale = "de_DE.utf8";
if($locale == "fr") 
    $locale = "fr_FR.utf8";

putenv("LC_ALL=$locale");
setlocale(LC_ALL, $locale);

// Specify location of translation tables
bindtextdomain("translation", "locale");

// Choose domain
textdomain("translation");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
//echo _("title");
?>

and the link:

...
<a href="?setLang=en" onClick="window.location.reload( true );">en</a>
...
  • 写回答

2条回答 默认 最新

  • dougan6982 2013-04-16 19:33
    关注

    setcookie() adds a header to the output and does not alter the $_COOKIE superglobal.

    if (isSet($_GET['setLang'])) {
        $locale = $_GET['setLang'];
        setcookie('lang', $locale);
    } elseif (isSet($_COOKIE['lang'])) {
        $locale = $_COOKIE['lang'];
    } else {
        $langs = array('en-US', 'fr', 'fr-FR', 'de', 'de-DE', 'de-AT', 'de-CH');
        $locale = substr(http_negotiate_language($langs), 0, 2);
    }
    

    will do what you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助