Auto detect language and redirect user Auto detect language and redirect user php php

Auto detect language and redirect user


Well, I came across some problems with my code which is no surprise due to I am not a PHP expert. I kept therefore on searching for a possible solution and I found the following code on another website:

<?php    // Initialize the language code variable$lc = "";     // Check to see that the global language server variable isset()    // If it is set, we cut the first two characters from that stringif(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))    $lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);    // Now we simply evaluate that variable to detect specific languagesif($lc == "fr"){    header("location: index_french.php");    exit();} else if($lc == "de"){    header("location: index_german.php");    exit();}else{ // don't forget the default case if $lc is empty    header("location: index_english.php");    exit();}?>

This did the job perfectly! I only had a problem left. There was no way to change language, even with direct links into another language because as soon as the page was loading, the php block would redirect me to the borwser's language. This can be a problem if you are living in another country and have for instance Swedish as a mother language but you have your browser in English because you bought your computer in the UK.

So my solution for this issue was to create folders with a duplicate version for every language (even the one for the main language) without this php code on the index.html (and therefore not index.php). So now my website is auto detecting the language and the user also has the option to change it manually in case of they want!

Hope it will help out someone else with the same problem!


PHP 5.3.0+ comes with locale_accept_from_http() which gets the preferred language from the Accept-Language header.

You should always prefer this method to a self-written method as the header field is more complicated than one might think. (It's a list of weighted preferences.)

You should retrieve the language like this:

$lang = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);

But even then, you won't just have en for every English user and es for Spanish ones. It can become much more difficult than that, and things like es-ES and es-US are standard.

This means you should iterate over a list of regular expressions that you try and determine the page language that way. See PHP-I18N for an example.


I think your idea is great. May be help you shortest code:

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);header("location: ".$lang."/index.php");