1

I am wondering about CI best practices

I need to have some code that detects the browser's language and assigns the appropriate language file.

does such code belongs under library or helper? ( if i am right helpers are php functions as opposed to libraries which are classes )

also what would be the best way to launch a class as opposed to just load it.

thank you.

icchanobot
  • 3,323
  • 27
  • 37
salmane
  • 4,799
  • 13
  • 48
  • 61

2 Answers2

3

You can get language information from a browser with:

$this->input->server('HTTP_ACCEPT_LANGUAGE');

Mine returns en-US,en;q=0.8 so you will need to do some parsing to translate that into something useful to you.

But then you can set the language which CI uses to load language files with

$config['language'] = 'english';

where 'english' is the name of the folder in your application/languages folder which contains your language files.

You can do those things anywhere before your code runs. I'd recommend making a application/libraries/MY_Lang.php (application/core/MY_Lang.php in 2.0) and putting it in the constructor, cos then its always loaded before you use a language file.

Lastly should read this. But basically you retrieve a line from your language file with:

$this->lang->line('language_key');
icchanobot
  • 3,323
  • 27
  • 37
2

PHP has a function called get_browser to detect user's browser. I think that the best practice is:

  1. Set a front controller to get user's browser using Javascript.
  2. Redirect the user to an appropiate function, to set language and load your main view.

Anyways, on Google I found a few snippets:

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

And from here, on StackOverflow: Checking browser's language by php

Community
  • 1
  • 1
Fran Verona
  • 5,438
  • 6
  • 46
  • 85