2:38 PM 11/1/2019 -
An example of this is when a user needs to read a webpage in his / her own native language. He / she may change this with a click of a button and page will redirect to a proper page.
From my point of view, this can be implemented in following way:
First, webpages / contents for a language should be organized in a specific directory, and other languages in other separate directories. For example, if we have pages in English, Indonesian and German, we should create 3 directories to store pages as follows:
<?php session_start(); if($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['lang']){ $_SESSION['lang'] = $_GET['lang']; if($_SESSION['lang'] === 'en') header('Location: /' . $_GET['page']); elseif($_SESSION['lang'] === 'id') header('Location: /id/' . $_GET['page']); elseif($_SESSION['lang'] === 'de') header('Location: /de/' . $_GET['page']); } ?>
User may change language with a click to an anchor link to get Indonesian version of a page like:
<a href="/redir.php?lang=id&page=<?php echo basename($_SERVER['SCRIPT_NAME']);?>
Problem arises however when that user (accidentally / not) goes back to previous page via browser's history back button. User does get back to an English page but his / her preference is still Indonesian, correct?
To handle this, each pages (in any languages) must be preceded with following code:
<?php session_start(); if(!isset($_SESSION['lang'])) //set default language to English $_SESSION['lang'] = 'en'; /*requested page (sub folder) may be different than selected language recorded by session, as user clicks browser back button. in such case, perform redirection to proper page based on language.*/ $page = basename($_SERVER['SCRIPT_NAME']); $subdir = ltrim(dirname($_SERVER['SCRIPT_NAME']), '/'); if( ($_SESSION['lang'] == 'en' && $subdir != '') || ($_SESSION['lang'] == 'id' && $subdir != 'id') || ($_SESSION['lang'] == 'de' && $subdir != 'de')){ header('Location: /redir.php?lang='. $_SESSION['lang']. '&page=' . $page); exit; } ?> <!DOCTYPE html> <html lang="<?php echo $_SESSION['lang'];?>"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
Hopefully I'll have sometime to make a demo of this. To be continued then :)
Comments