patternphpMinor
Language-detection PHP script
Viewed 0 times
scriptphpdetectionlanguage
Problem
I'm working on a webpage with language detection and I have the following script so far (it's simple). I still haven't done the user detection, so it's not available to find the user language (yet), but this will be easily implemented. Though I'm not asking for that, I'm asking for other ways to improve this code. So far as I've tested it, it's bug-free, but I want it to be bulletproof. How can I improve or expand it?
//LANGUAGES
//Language detection
if ( !empty($_POST['lang']) )
{
$Lang = $_POST['lang'];
$_SESSION['lang']= $_POST['lang'];
}
else
{
if ( !empty ($_SESSION['lang']))
$Lang = $_SESSION['lang'];
else
$Lang = substr ($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
//After this, $Lang will have the webpage preferenceSolution
On principle the code is sound except for one issue: you do not check if the language is "valid". This raises some questions:
In both cases, the sane outcome would be to default to your "main" language, which would probably be hardcoded in your application.
Another issue you may want to consider is that nobody knows that there is an Accept-Language header and how to use it, so using that as a source of the user's preferred locale is not recommended:
It is not a good idea to use the HTTP Accept-Language header alone to
determine the locale of the user. If you use Accept-Language
exclusively, you may handcuff the user into a set of choices not to
his liking.
In your shoes I would totally scrap using
- How will your localization code behave if I added a
langparameter with the value"foobar"?
- How will it behave if I try to do an SQL injection using the parameter value?
In both cases, the sane outcome would be to default to your "main" language, which would probably be hardcoded in your application.
Another issue you may want to consider is that nobody knows that there is an Accept-Language header and how to use it, so using that as a source of the user's preferred locale is not recommended:
It is not a good idea to use the HTTP Accept-Language header alone to
determine the locale of the user. If you use Accept-Language
exclusively, you may handcuff the user into a set of choices not to
his liking.
In your shoes I would totally scrap using
$_SERVER['HTTP_ACCEPT_LANGUAGE'] (IMHO it's useless in practice). If you want to go the extra mile and auto-detect the user's locale, use an IP database (I have used MaxMind GeoIP in the past myself) or the upcoming W3C geolocation spec.Context
StackExchange Code Review Q#9141, answer score: 6
Revisions (0)
No revisions yet.