Change the language of a site using a button

Joscplan picture Joscplan · Jun 15, 2013 · Viewed 8.8k times · Source

Hi I want as the title says change the language of the site using a button but this without altering the url mywebsite.com (Without doing mywebsite.com?lang=es) by just changing PHP variables in this code:

$xlang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);


if($xlang == "es")
{
$g_lang = "es";
}
else if ($xlang == "en")
{
$g_lang = "en";
}
else
{
$g_lang = "en";
}

And then using this button

<a class="langx" href="#"></a>

Change the language without altering the url

Is there a way to do that? if so, how?

Thanks in advance.

Answer

jeroen picture jeroen · Jun 15, 2013

You need to send the required value to the server when the button is clicked, so your link would have to have the language string like ?lang=es.

Then you can process it on the server side and store the language for the current visitor in for example a database (for logged-in users), a session or a cookie.

Then you can use a header redirect to redirect the user to the site without the language string and check at the top if the db-entry / session / cookie is set and use that language.