viriato viriato - 2 years ago 137
PHP Question

Auto detect language and redirect user

I am doing my own website and I managed to write some code that makes directs user to the language version according to the browser's language. Here is the script:

header("location: index.php");
header("location: pt/index.php");
header("location: en/index.html");

I have put this in the index.php before the . It seems to be working because I am not in an English speaking country but my browser is in English and I am being redirected to the English version.

Is this correct? Is there a better/cleaner way to do this?

Answer Source

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:

    // 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 string
    $lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

    // Now we simply evaluate that variable to detect specific languages
if($lc == "fr"){
    header("location: index_french.php");
} else if($lc == "de"){
    header("location: index_german.php");
else{ // don't forget the default case if $lc is empty
    header("location: index_english.php");

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download