codeignitercontrollermultilingualbase-url

Language switch based on domain (base_url switch) - what's the best practice?


Q: I've got a multilanguage site. Where the language is switched automatically by checking the base url, let's assume www.myapp.fr (for French) and www.myapp.es (for Spanish). I use a helper function to do $this->config->set_item('base_url', $domain) accordingly. My question is, where should I place the helper function, the best scope, so that the user is not trapped into seeing the French site, with the wrong url www.domain.es ? MY_Controller constructor ?

(*) Usually people have one domain name for a multilanguage site. In my case, I've got same hosting with two domain names pointing to it. Based on the user request uri, I do the switch!

I'm rewriting a website that does this, and is working fine. But I remember having a few issues, because the base_url wasn't switched properly and users where navigating in language FR while in domain ES (example). In that time, I didn't had a helper on each controller, no DRY good practice, so I guess that, this was the problem. But 90% it worked fine!


Solution

  • Don't set base_url yourself.

    CI 2.0 onwards you don't need to set base_url.

    you can use this code to set the base_url

    $config['base_url'] = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') ? 'https://' : 'http://' . $_SERVER['HTTP_HOST'];
    

    Now, that you are free from base_url. You can have a hook to determine what language to use based on domain name.