phpmultilinguallanguage-switching

PHP: A way to manually switch languages?


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

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?


Solution

  • 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';