I
I
Ilkhom Nazarov2015-11-30 23:31:16
PHP
Ilkhom Nazarov, 2015-11-30 23:31:16

How to show language versions of a site using php?

The url is selected based on the language settings in the user's browser. Is it possible to use php (without using redirects in .htaccess) to implement 3 languages ​​on the site?
to be like this:
site.de/ - German version
site.de/ru/ - Russian version
site.de/en/ - English version
Not like this:
site.de/de/
site.de/ru/
site.de/en /

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arseny Sokolov, 2015-12-10
@ArsenBespalov

It is possible, but for the most part it depends on the CMS engine of your site, if you are inventing a bicycle, then here is a sketched implementation of what you are talking about:

class Language
{
  var $language = null;

  public function __construct()
  {
    if (($list = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']))) {
      if (preg_match_all('/([a-z]{1,8}(?:-[a-z]{1,8})?)(?:;q=([0-9.]+))?/', $list, $list)) {
        $this->language = array_combine($list[1], $list[2]);
        foreach ($this->language as $n => $v)
          $this->language[$n] = $v ? $v : 1;
        arsort($this->language, SORT_NUMERIC);
      }
    } else $this->language = array();
  }

  public function getBestMatch($default, $langs)
  {
    $languages=array();
    foreach ($langs as $lang => $alias) {
      if (is_array($alias)) {
        foreach ($alias as $alias_lang) {
          $languages[strtolower($alias_lang)] = strtolower($lang);
        }
      }else $languages[strtolower($alias)]=strtolower($lang);
    }
    foreach ($this->language as $l => $v) {
      $s = strtok($l, '-'); // убираем то что идет после тире в языках вида "en-us, ru-ru"
      if (isset($languages[$s]))
        return $languages[$s];
    }
    return $default;
  }
}

This is how you will use it:
// Определяем для кого будет выбираться русский язык
$site_langs = array('ru' => array('ru', 'be', 'uk', 'ky', 'ab', 'mo', 'et', 'lv'));

// Опеределяем язык пользователя и выбираем нужный для сайта
$user_lang = new Language();
$current_lang = $user_lang->getBestMatch('de', $site_langs);

// Отправляем пользователя на нужный язык для его локали.
if ($user_uri == '/') {
    if ($current_lang != 'de') {
        header("Location: http://site.de/" . $current_lang . "/");
    }
}

A
Andrey, 2015-12-11
@a_ovchinnikov

And why are you not satisfied with the redirect at the web server level? If you use nginx, then it will not be difficult to do it there, and most importantly, it will work much faster than the PHP implementation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question