John Shepard
John Shepard

Reputation: 947

CodeIgniter 2.1 internationalization i18n - Override default language if user data exists

I am running CI version 2.1 and I have recently installed the CodeIgniter 2.1 internationalization i18n (Original Author: Jérôme Jaglale). The code instructions are here: http://codeigniter.com/wiki/URI_Language_Identifier/

It runs fine but I would like to override the default language if the user set his language preference in a previous visit to the website (this would be stored in a table in the database).

My question is, how do you do this?

I believe MY_Lang.php (where default language is loaded) is actually loaded BEFORE the CodeIgniter MY_Controller so I am unable to load the database to find if a user has a preferred language.

The default language is configured in MY_Lang.php here:

function default_lang()
{
    $browser_lang = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtok(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE']), ',') : '';
    $browser_lang = substr($browser_lang, 0,2);
    $default_lang = array_splice(array_keys($this->languages), 0,1); 
    return (array_key_exists($browser_lang, $this->languages)) ? $browser_lang : $default_lang[0]; 
}

However, I am unable to override it because here I have no access to my $this->session->userdata('language')

Thanks in advance!


ANSWER HERE:


Found out that you can use native PHP cookies to read the cookie inside MY_Lang.php file. If you try to use the cookie helper it won't work, so make sure you use $_COOKIE instead and run the appropriate filters before getting the content.

Then, in MY_Lang.php just change this:

return (array_key_exists($browser_lang, $this->languages)) ? $browser_lang : $default_lang[0]; 

To this:

if($_COOKIE['int_lang']) {
$preferred_lang = filter_var($_COOKIE['int_lang'], FILTER_SANITIZE_STRING);
return (array_key_exists($preferred_lang, $this->languages)) ? $preferred_lang : $default_lang[0];
}
else
{
return (array_key_exists($browser_lang, $this->languages)) ? $browser_lang : $default_lang[0]; 
}

Upvotes: 3

Views: 2572

Answers (1)

conradkleinespel
conradkleinespel

Reputation: 6987

If it was me, I'd use cookies for that instead of storing this in a database. It'll be faster and easier to manage.

Most users don't erase cookies, at least not all that often. It would solve your problem: "I am unable to load the database to find if a user has a preferred language".

If you need the database storage, you could try using a Hook: http://codeigniter.com/user_guide/general/hooks.html

In a "post_controller_constructor" hook, load you Database Model used for language storage, get the language set by the user and load the language file that you want.

Upvotes: 2

Related Questions