Codeigniter, language switch based on domain (base_url switch) whats the best practice?
-
15-11-2019 - |
Question
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 peolpe 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 rewritting 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 didnt had a helper on each controller, no DRY good practice, so I guess that, this was the problem. But 90% it worked fine!
Any tips is appreciated ;D
Thanks a lot
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.