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>
...
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.