Language-detection PHP script 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 preference
On principle the code is sound except for one issue: you do not check if the language is "valid". This raises some questions:


How will your localization code behave if I added a lang parameter 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.