Language switcher

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

By gregThomas - January 23, 2014

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

By mattbcd - January 24, 2014

Hi Greg

It worked a treat. Thank you sooo much! Also, thanks for not laughing at my appalling code - as a relative newbie one can be too embarrassed to ask for help. Particularly when the answer is staring you in the face. So you are officially 'good people'. Thank you.

Matt