N
N
Nikolay2015-04-23 01:38:26
PHP
Nikolay, 2015-04-23 01:38:26

How to implement multilingualism in php using cookies?

setcookie('lang', $_POST['lang']);

if(session_start()) {
    $_SESSION['lang'] = $_COOKIE['lang'];
} else {
    $_SESSION['lang'] = $_POST['lang'];
}

$lang = $_SESSION['lang'];

$defaultlang = 'rus';

if (!isset($lang))
{
   $lang = (!file_exists("./lang/{$lang}.php")) ? $defaultlang : $lang;
}

echo "lang=".$lang;

require "./lang/{$lang}.php";

<form action="?set=lang" method="post">
        <select name="lang">
            <option value="rus">ru</option>
            <option value="eng">en</option>
        </select>
        <input type="submit" value="ok" />
    </form>

The main problem is that it only reaches the cookie the second time.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg ak-o, 2015-04-23
@ak-o

As an option, parse the "Accept-Language" header and immediately issue the "preferred language" along with the cookie. Which, say, we change if necessary (when choosing another language through the select, we update the page, load the desired language and set the cookie)
I use the following scheme for myself:
site.ru/some_page
site.ru/en/some_page
You can also ru.site.ru / en.site.ru, etc. I
use this scheme because search engines look for special links on the page, which, as it were, say that this page exists in N languages. Thus, they understand that this is the same content.

K
KIN1991, 2015-04-23
@KIN1991

to implement multilingualism through cookies is not a good practice, it is better to implement it through url.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question