PHP: A way to manually switch languages?

4.2k views Asked by At

I have a website that has the following language switching algorithm:

  • First, it detects the default browser language (I do not know why? but Chrome always gives something like en-EN,ru,lv, so Chrome's default language always is English, it seems).
  • Then it writes the language value into a session variable lang and requests the desired string file (i.e. /assets/includes/en-US/strings.php);
  • And every string from this file is being included in the HTML code, so the pure HTML has not any plain text in.

Of course, a default language detection is not the reason to stop - I need a manual language switcher like links (LV | EN | RU). So, what id the possible (and maybe the best) way to switch the language and to overwrite the session variable after user clicks to the desired language?

1

There are 1 answers

3
Royal Bg On BEST ANSWER

The best way is the simpliest way :)

$langs = array('LV', 'EN', 'RU');

<?php foreach ($langs as $lang): ?>
    <a href="index.php?lang=<?=$lang;?>"> <?=$lang;?> </a>
<?php endforeach; ?>

so you give the user opportunity to change lang via GET in this example.

Overwrite the session to the sent request:

<?php
if(in_array($_GET['lang'], $langs) {
    $_SESSION['lang'] = $_GET['lang']; // to prevent user to change its session to something you don't want to
}
?>

Afterwards you just interact with this session to display content.

You can use redirection, if you have each page written in different language: (but I guess the logic how to interact with the language you have already implemented from the automatic language detection, but still... let me suggest some ways at fast?)

<?php
if (isset($_SESSION['lang']) && $_SESSION['lang'] !== 'EN') {
    header("Location: mysite.com/".$_SESSION['lang']."/index.php");
    exit;
}
?>

Or, you can use translation method.

All of your translations are in a database under columns with the same names as your $langs array.

So you output the content from this particular column:

SELECT lang_{$_SESSION['lang']} FROM translations WHERE string = '$string';