Synchronizing user preference and browser history

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:

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:

	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);
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['lang'];?>">
		<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 :)