Skip to content

Instantly share code, notes, and snippets.

@artoodetoo
Created March 18, 2015 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artoodetoo/9c98a3c4fabac13e4f32 to your computer and use it in GitHub Desktop.
Save artoodetoo/9c98a3c4fabac13e4f32 to your computer and use it in GitHub Desktop.
Internationalization functions: user preffered language and translate
<?php
function userLanguage(array $preferred = ['en', 'ru'])
{
static $language;
// calculate preferred language and do it only once
if (!isset($language)) {
$language = $preferred[0];
// user has choosen the language
if (isset($_COOKIE['lang']) && in_array($_COOKIE['lang'], $preferred)) {
$language = $_COOKIE['lang'];
// the language are set in browser settings
// for ex. Accept-Language=en-ca,en;q=0.8,en-us;q=0.6,de;q=0.2
} elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])
&& preg_match_all(
'/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i',
$_SERVER['HTTP_ACCEPT_LANGUAGE'],
$matches
)) {
$langs = array_combine($matches[1], $matches[4]);
foreach ($langs as $lang => $val) {
if ($val === '') {
$langs[$lang] = 1;
}
}
arsort($langs, SORT_NUMERIC);
$intersect = array_intersect(array_keys($langs), $preferred);
if (reset($intersect)) {
$language = current($intersect);
}
}
}
return $language;
}
function t($str)
{
static $phrases;
// get language + dictionary and do it only once
if (!isset($phrases)) {
$lang = userLanguage();
$filename = __DIR__."/i18n/{$lang}.php";
$phrases = file_exists($filename) ? include($filename) : [];
}
// get translation or original phrase
return isset($phrases[$str]) ? $phrases[$str] : $str;
}
@artoodetoo
Copy link
Author

Usage example:

<?php

require __DIR__.'/i18n.php';

// User language choice handler
if (isset($_GET['lang'])) {
  setcookie('lang', $_GET['lang'], 0, '/');
  $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'index.php';
  header('Location: '.$ref);
  exit();
}

?>
<!DOCTYPE html>
<head>
<title><?= t('My site') ?></title>
<meta charset="utf-8">
<style>
.wrap { width: 980px; margin: 0 auto; }
header { overflow: hidden; border-bottom: 1px solid #000; }    
.title { float: left; font-size: 1.4em; }
.lang-switch { list-style: none; float: right; }
.lang-switch li { display: inline-block; }
</style>
</head>
<body>
<header class="wrap">
  <p class="title"><?= t('My site') ?></p>
  <ul class="lang-switch">
    <li><a href="index.php?lang=ru">ru</a></li>
    <li><a href="index.php?lang=en">en</a></li>
  </ul>
</header>
<div class="content wrap">

  <p class="exclamation"><?= t('Show must go on!') ?></p>

  <p><?= isset($_COOKIE['lang']) 
    ? 'Cookie[lang]='.$_COOKIE['lang']
    : 'Accept-Language='.$_SERVER['HTTP_ACCEPT_LANGUAGE'] ?></p>
</div>
</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment