Language switcher

3 posts by 2 authors in: Forums > CMS Builder
Last Post: January 24, 2014   (RSS)

By mattbcd - January 21, 2014

I've been trying to create a simple language switcher (Eng & Ger).  I've created duplicate fields for each piece of content, ending in _en or _de  Then created links for each ending in ?lan=eng and ?lan=de

A test version can be seen at:

http://www.premiergolfacademy.com/aboutTest.php

Everything works up to a point, but when you click the links, which sets a cookie, you only get the correct language when you click again, or refresh. The PHP which select the correct content from the cookie setting is:

<?php if(@$_COOKIE['langCookie'] == "de"): ?>
    <?php echo htmlencode($aboutRecord['title_de']) ?>
    <?php else: ?>
    <?php echo htmlencode($aboutRecord['title_en']) ?>
    <?php endif ?>

and the PHP which sets the cookie is:

<?php

function setLanguage ()
{
    if(isset($_GET['lan']))
    {
        if($_GET['lan'] == 'de')
        {
            setcookie('langCookie','de',time()+60*60*24*365);
        }
        else
        {
            setcookie('langCookie','en',time()+60*60*24*365);
        }
    }
    else
    {
        setcookie('langCookie','en',time()+60*60*24*365);
    }
}

function checkLangCookie ()
{
    if(isset($_COOKIE['langCookie']))
    {
        if($_COOKIE['langCookie'] == 'de')
        {
            setcookie('langCookie','de',time()+60*60*24*365);
        }
        else
        {
            setcookie('langCookie','en',time()+60*60*24*365);
        }
    }
    else
    {
        setcookie('langCookie','de',time()+60*60*24*365);
    }
}
checkLangCookie();
setLanguage();

?>

I'm sure this part is the problem - would anyone be able to help?

Hi  mattbcd 

I think the problem here is that PHP sets the $_COOKIE variable before it starts running the PHP code for the page. So the current order of things is:

  1. Your cookie currently contains German as the language.
  2. You click the English link, the page reloads.
  3. PHP gets the contents of the cookie, and sets it to the $_COOKIE variable, at this point the language is still German.
  4. PHP runs the code on the page, as the English link is clicked the contents of the cookie gets set to English, but it doesn't update the $_COOKIE variable.  

The easiest way around this issue is to just set the contents of the $_COOKIE variable manually when you update the cookie:

function setLanguage (){
    if(isset($_GET['lan'])){
        if($_GET['lan'] == 'de'){
            setcookie('langCookie','de',time()+60*60*24*365);
            $_COOKIE['langCookie'] = 'de';
        }else{
            setcookie('langCookie','en',time()+60*60*24*365);
            $_COOKIE['langCookie'] = 'en';
        }
    }else{
        setcookie('langCookie','en',time()+60*60*24*365);
    }
}

Let me know if you have any questions.

Thanks!

Greg

Greg Thomas







PHP Programmer - interactivetools.com