First of all, I must precise that I'm quite a noob in web development, but I'll do my very best.
I created a multingual website in English and French. Contrary to most people I read on the internet that advise to create a different php page per language, I created a MySql array to have a proper localization of the website. I find this solution much cleaner and more elegant, as I plan to add more languages sooner or later.
I have a Config.php
file with the path to MySql. By default, language is English, unless you decide to display another language, like French :
$_SESSION['lang'] = "en";
}
else{
switch($_GET['lang']){
case "fr":
$_SESSION['lang'] = "fr";
break;
case "en":
$_SESSION['lang'] = "en";
break;
default :
$_SESSION['lang'] = "en";
break;
}
}
switch($_SESSION['lang']){
case "fr":
$language = "French";
break;
case "en":
$language = "English";
break;
}
Obviously, Config.php
is included in all other php pages.
In order to change the language, I added images with flags in the navigation bar, which will add a ?lang=
at the end of the url :
<a href="?lang=fr"><img class="language" src="images/fr.png"></a>
<a href="?lang=en"><img class="language" src="images/en.png"></a>```
So, if you choose French, it adds ?lang=fr
to the url. Localization works great, I'm happy.
However, when I navigate to a different page from the navigation bar, it loses the French language (as English is the default one) :
<a href="index.php"><?php echo $loc["header_home"] ?></a>
I understand that it makes sense since the link is only index.php
and not index.php?lang=fr
.
So, I tried to go for cookies in order to keep the chosen language, and this is where I'm stuck.
I edited my Config.php
to set and Cookies like this :
if ((isset($_GET['lang']) != "")) {
setcookie("langpref", "".$_GET['lang'] ."", time()+(0), "/", 'domain.com'); //expires at the end of the session//
$_COOKIE['langpref'] = $_GET['lang'];
}
No problem so far, until I add these lines :
if (isset($_COOKIE['langpref'])) {
if (strpos($_SERVER['PHP_SELF'],$_COOKIE['langpref']) === false) {
header("location: ". basename($_SERVER['PHP_SELF']). "?lang=". $_COOKIE['langpref'] );
}
}
I assume this is a naive approach to add ?lang=
in the url like this.
Because when I do, I've got an error message that says the page cannot be loaded because cookies are not allowed or something.
Any help (or different approach) would be welcome !
Thank you in advance !