I have an option to switch between languages and it works perfectly fine - the problem is, that url is staying the same and I need to make it dynamic in order if the link is shared in particular language selection. Any idea how can I implement it ?
LanguageSwitcher.php
<?php
session_start();
if($_GET['la']){
$_SESSION['la'] = $_GET['la'];
header('Location:'.$_SERVER['PHP_SELF']);
exit();
}
switch($_SESSION['la']){
case "en":
require('lang/en.php');
break;
case "dk":
require('lang/dk.php');
break;
default:
require('lang/en.php');
}
?>
Dropdown :
<li><a class="dropdown-item" href="index.php?la=en"><img class="ml-3" src="assets/images/flag_uk.png" alt="<?=$lang['lang-en'];?>" title="<?=$lang['lang-en'];?>" style="width: 25px;"/><span class="ml-3"><?=$lang['lang-en'];?></span></a></li>
<li><a class="dropdown-item" href="index.php?la=dk"><img class="ml-3" src="assets/images/flag_dk.png" alt="<?=$lang['lang-dk'];?>" title="<?=$lang['lang-dk'];?>" style="width: 25px;"/><span class="ml-3"><?=$lang['lang-dk'];?></span></a></li>
The main requirement is to not store the language in the session and instead always provide the language in the URL, which is a little work because you need to update all URLs on all pages.
There're two ways coming to mind, and deciding for one kind of depends on personal preference.
Using
GET/REQUESThttps://example.com/subpage?la=enUpdate all URLs on all pages to include the language like this:
Note:
htmlspecialcharsconverts special HTML characters to prevent chross-site scripting.Example:
index.php
lang/en.php
Using a Request Router
https://example.com/en/subpageCan be achieved by either using a library for that specific case (there are plenty in the wild) or using a framework, preferably a micro framework for the beginning. My personal recommendation would be Slim, a very simple yet powerful PHP micro framework.
Install the library or framework of your choice (most use composer for that - read their docs for how to do that). Then, update all URLs on all pages to include the language like this:
Example (for Slim):
index.php
lang/en.php
A little side note to translation mechanics
There's an advanced way to translate content, which fits well with above mentioned approaches. That is, by wrapping all translatable content into method calls, which then lookup translation files and return the translated content for the provided language setting. Frameworks usually provide this mechanic by default (such as Symfony's Translation or Laravel's Localization).
It's not directly related to the original problem, but worth a mention and some reading.