skip to Main Content

I’m using quite a simple and straightforward session switch to make my site bilingual. However it has a flaw – as soon as you switch to the other language, it throws you back on the index. I would like to have a solution where the user stays on the same page on which he/she has decided to change the language.

Language switch program:

 <?php session_start();

// Define a list of supported languages to avoid arbitrary file inclusion
$supportedLanguages = ['en', 'da'];

if (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = "en";
} else if (isset($_GET['lang']) && in_array($_GET['lang'], $supportedLanguages)) {
    $_SESSION['lang'] = $_GET['lang'];
}
// Ensure the requested language file exists before requiring it
$languageFile = "languages/" . $_SESSION['lang'] . ".php";
if (file_exists($languageFile)) {
    require_once $languageFile;
} else {
    // Handle the case where the language file doesn't exist (e.g., fallback to a default language).
    // You can add code here to provide a graceful error message or take other appropriate actions.
    die("Language file not found.");
}
?>

HTML Swich interface:

  <li role="menuitem">
            <?php if($_SESSION['lang']=="da"){
              echo '<a class="language-switch" href="/?lang=en">EN</a>';
            }
            else if($_SESSION['lang']=="en"){
              echo '<a class="language-switch" href="/?lang=da">DA</a>';
            } ?>
          </li>

2

Answers


  1. To stay on the same page when switching languages, you can include the current page URL in the language switch links. This way, when a user changes the language, the script will redirect them to the route with the new language parameter. Here’s an updated version of your code:

    Language switch program:

    <?PHP
    ... // you logic
    
    // Get the current page URL
    $currentUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
    
    ... // any other logic 
    ?>
    

    HTML Swich interface:

      <li role="menuitem">
         <?php if($_SESSION['lang']=="da"){
            echo '<a class="language-switch" href="' . $currentUrl . '/?lang=en">EN</a>';
           }
           else if($_SESSION['lang']=="en"){
            echo '<a class="language-switch" href="' . $currentUrl . '/?lang=da">DA</a>';
           } ?>
     </li>
    
    Login or Signup to reply.
  2. You could use JavaScript’s Fetch API to do so. By default, it doesn’t send your Session cookie with a request, but you can add the credentials: true flag to it.

    JavaScript:

    function switchLanguage(langCode) {
        // Change langswitch.php to the path which is actually responsible for that
        fetch(`/langswitch.php?lang=${langCode}`, {
            credentials: "same-origin"
        }).then(() => {
            window.location.reload();
        }).catch((error) => {
            console.log("There was an error while switching languages");
        });
    }
    

    HTML Switch interface:

    <li role="menuitem">
       <?php if($_SESSION['lang']=="da"){
          echo '<a class="language-switch" onclick="switchLanguage('en')">EN</a>';
       }
       else if($_SESSION['lang']=="en"){
          echo '<a class="language-switch" onclick="switchLanguage('da')">DA</a>';
       } ?>
    </li>
    

    This way, you wouldn’t even have to leave the site, it just reloads after sending the request to the server.

    There is no response specific error handling implemented, this JavaScript just assumes that your server will handle all the possible errors for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search