Search code examples
phplocalesession-cookiestranslate

Translate site using session in php


I try to translate my site using PHP and make it to remind the language even if the user navigate between pages and I can't do it in the way I want. The way I want is using a 'locale' folder.

The main file is called index.php that can contain something like this:

<?php
include "locale/en.php";
echo $locale['test'];
?>

..and the en.php is in "locale" folder near "it.php", "ro.php", "fr.php" and so on. En.php file contains:

<?php
$locale['test'] = "anything";
?> 

Now here's the problem.. I know the term "session" in php, but I don't know how to make this syntax work in PHP.

session_start();
if user clicks the Italy flag{
translate the site in italian;
}else{ 
if the user click the France flag{
translate the site in french
}else{...

I wish when the user navigate between pages to see the content in language that he selected. Optionally to store the language that he selected in a cookie to see the site in language that he wants even if comes back to site second, third... time. Thanks, and sorry for my bad language :)


Solution

  • One way of doing it is:

    session_start(); //include this at the top of your page(s)
    
    if(!isset($_SESSION['language'])){
        $_SESSION['language'] = 'en'; // set the default language
        }
    
    if(isset($_GET['setLanguage'])){
        $_SESSION['language'] = $_GET['setLanguage']; //if the user change language
        }
    
    $allowedLanguages = array('en','es');  
    
    if(in_array($_SESSION['language'],$allowedLanguages)){
       include('languages/'.$_SESSION['language'].'.php');
       }
    

    Then the language files would look like:

    en.php:

    $header = '<h1>My header</h1>';
    

    other language, e.g. es.php:

    $header = '<h1>Mi encabezado</h1>';
    

    At the page, you then refer to the variable $header instead of hardcoding the text. As the language file, where the value of the variables changes depending on the chosen language that the session variable holds, the content of your page will change accordingly.