Hello,
I am a beginner with PHP, and I have made a language switcher on a site
that I am looking for your feedback on.
First of all, the page is http://www.mankar.ca
My question regarding usage is - well, does it work? Can you continue
browsing in your selected language? I am especially interested in people
using an IE browser with a locale setting that is not english or french.
I'll post the code below as well - I'm the first to admit it isn't
pretty, and I'll try to explain the result I am trying to achieve:
1)if they are already on my site and have chosen a language, use that
language.
2) barring that, try to serve the page in the language of their locale.
3) If I don't have their language, serve them English.
4) Regardless of language, they would be surfing the same web address.
So first I had only this:
if (isset($HTTP_GET_VARS['lang'])) {//check to see if they came from a
page where they set the language - like if we are switching languages on
the same page
$lang=$HTTP_GET_VARS[lang];
}
elseif(isset($_SESSION['lang'])){ //see if they already chose a language
$lang = $_SESSION['lang'];
}
elseif (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {//check second to see
if they've been nice and set the language
$langs=explode(",",$_SERVER["HTTP_ACCEPT_LANGUAGE"]);//grab all
the languages
foreach ($langs as $value) {//start going through each one
//select only the first two letters
$choice=substr($value,0,2);
//redirect to the different language page
//based on their first chosen language
switch ($choice) {
case "fr":
$lang = 'fr';
case "en":
$lang = 'en';
}
}
}
else{
$lang = 'en';
}
Which seemed to work, but had the problem that people with IE with a
different locale couldn't use the site (this code triggers a number of
includes), so I added this to the beginning:
if ($lang == 'fr') {
$lang = 'fr';
}
else{
$lang = 'en';
}
Which seems strange, but perhaps it works? It seems to work for me with
Firefox in various languages, as well as IE. Does anyone have any
suggestions to improve this code?
Here it is completely:
<?php
session_start();
if ($lang == 'fr') {
$lang = 'fr';
}
else{
$lang = 'en';
}
if (isset($HTTP_GET_VARS['lang'])) {//check to see if they came from a
page where they set the language - like if we are switching languages on
the same page
$lang=$HTTP_GET_VARS[lang];
}
elseif(isset($_SESSION['lang'])){ //see if they already chose a language
$lang = $_SESSION['lang'];
}
elseif (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {//check second to see
if they've been nice and set the language
$langs=explode(",",$_SERVER["HTTP_ACCEPT_LANGUAGE"]);//grab all
the languages
foreach ($langs as $value) {//start going through each one
//select only the first two letters
$choice=substr($value,0,2);
//redirect to the different language page
//based on their first chosen language
switch ($choice) {
case "fr":
$lang = 'fr';
case "en":
$lang = 'en';
}
}
}
else{
$lang = 'en';
}
$_SESSION['lang'] = $lang;
?>