Skip to content

Instantly share code, notes, and snippets.

@fgelinas
Created April 16, 2012 01:03
Show Gist options
  • Save fgelinas/2395687 to your computer and use it in GitHub Desktop.
Save fgelinas/2395687 to your computer and use it in GitHub Desktop.
Multilanguage site utility script
<?
/* _lang_util.php - Multilanguage site utility script
* This is my basic script to detect language and keep it in a cookie
*
* Language priority, from lowest to highest :
* - default lang
* - browser accepted lang
* - cookie lang
* - query parameter lang
*
* To switch lang, add query string lang=[lang_code]
*
* Francois Gelians
* http://fgelinas.com
* April 2012
*
*/
global $lang;
$langs = array('en', 'fr'); // site available languages, by priority
$lang = 'en'; // default lang
// detect browser lang, low priority
// here we keep the first lang in $langs that is accepted by the browser, not necessary the preferred browser lang.
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach ($langs as $lang_code) {
if ( strpos( $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_code ) > 0) {
$lang = $lang_code;
break;
}
}
}
// detect cookie lang, medium priority
if ( isset ($_COOKIE['lang']) ) {
if ( in_array( $_COOKIE['lang'], $langs ) ) {
$lang = $_COOKIE['lang'];
}
}
// detect lang in parameter, high priority
if ( isset ($_GET['lang']) ) {
if ( in_array( $_GET['lang'], $langs ) ) {
$lang = $_GET['lang'];
}
}
// save detected/selected lang in cookie
setcookie('lang', $lang);
// quick translate function, get text in current lang
// there is a problem here as this is built for a french/english site, update to your needs
function tr( $french, $english) {
global $lang;
if ($lang == 'fr') {
return $french;
} else {
return $english;
}
}
// basic lang check
function is_french()
{
global $lang;
return $lang == 'fr';
}
// basic lang check
function is_english()
{
return ! is_french();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment