[eluser]Kamil Rudnicki[/eluser]
If you want to set language based on URL, for example english for
www.domain.com and polish for
www.domain.pl you can use this funcion in your controllers constructors. It is very simple to use.
Code:
function setLanguage($dashboard = false)
{
$obj =& get_instance();
$languageToSet = false;
$obj->load->helper('cookie');
//if the user is logged in
if(isValidUser())
{
if($dashboard)
{
//set language based on logged users language
return;
}
}
//get domain name
$domain = str_replace("www.","",$_SERVER['HTTP_HOST']);
if($domain == 'localhost'){
$obj->lang->switch_to('polish');
return; //on localhost set lang to default
}
if($domain == 'domain.pl') $languageToSet = 'pl';
if($domain == 'domain.com') $languageToSet = 'en';
//if it is a bot don't redirect!
$obj->load->library('user_agent');
if ($obj->agent->is_robot())
{
if($languageToSet == 'pl') $obj->lang->switch_to('polish');
else $obj->lang->switch_to('english');
return;
}
//get language from browser
if(get_cookie('welcomeback') === false) //if the user is for the first time on site
{
$accept_langs = $obj->input->server('HTTP_ACCEPT_LANGUAGE');
$accept_langs = strtolower($accept_langs);
$accept_langs = explode(",", $accept_langs);
foreach ($accept_langs as $lang)
{
// remove all after ';'
$pos = strpos($lang,';');
if ($pos !== false)
{ $lang = substr($lang,0,$pos); }
// finish search if we support that language
if ($lang == 'pl' || $lang == 'en')
{
$languageToSet = $lang;
break;
}
}
}
//set the cookie
set_cookie('welcomeback', '1', 1036800);
//set language and/or redirect
if($languageToSet == 'pl' && $domain == 'domain.pl') $obj->lang->switch_to('polish');
else if($languageToSet == 'en' && $domain == 'domain.com') $obj->lang->switch_to('english');
else if($languageToSet == 'pl' && $domain == 'domain.com') header('Location: http://www.domain.pl/');
else if($languageToSet == 'en' && $domain == 'domain.pl') header('Location: http://www.domain.com/');
}
And in config.php:
Code:
$domain = str_replace("www.","",$_SERVER['HTTP_HOST']);
if(!($domain == 'domain.pl' || $domain == 'domain.com')) $domain = 'domain.pl';
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://www.".$domain."/";