redirect using HTTP_ACCEPT_LANGUAGE not working

Hi

I have this code that is supposed to redirect user according to his browser language but it doesn’t work.

[php]<?php
$lang = $_SERVER[‘HTTP_ACCEPT_LANGUAGE’];
switch($lang) {
case “de”:
case “ru”:
case “cn”:
case “fr”:
header(“Location: http://www.example.co.za/$lang/index.html”);
break;
default:
header(“Location: http://www.example.co.za/en/index.html”);
break;
}[/php]

When I use a Russian Firefox, I still get redirected to the “default” URL and not to the russian version as I should be. Furthermore, I did a test to echo out $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]; and this is what was returned:

ru,en-us;q=0.7,en;q=0.3

Thanks in advance for any help.

Your switch statement is looking for a string with the two letter country code in it. But you are setting $lang to the entire return of the HTTP_ACCEPT_LANGUAGE header.

This: en-US,en;q=0.8
and
This: “en”

are not the same, your switch will always land in the default.

THanks for the reply. So far the forum has been excellent in pointing out what is wrong. Would someone be kind enough to present a solution to this?

I’ll post one way of doing it, there is always different ways, and in no way is mine probably the best, but here is a possible solution that I think would work for you.

This works by taking the HTTP_ACCEPT_LANGUAGE response, breaking it apart by the comma and switching on the first two characters.

[php]<?php
$lang = $_SERVER[‘HTTP_ACCEPT_LANGUAGE’];
$lang_parts = explode(",", $lang);

switch(substr($lang_parts[0], 0,2)) {
case “de”:
case “ru”:
case “cn”:
case “fr”:
header(“Location: http://www.example.co.za/$lang_parts[0]/index.html”);
break;
default:
header(“Location: http://www.example.co.za/en/index.html”);
break;
}[/php]

Thanks for that, I kind of understand this. the only thing that confuses me is this part

$lang_parts[0]

Why is there a [0] there? I am assuming that the “0,2” means “take first two characters right?”

$lang_parts is an array, the result of split $_SERVER[‘HTTP_ACCEPT_LANGUAGES’];

Example:
$_SERVER[‘HTTP_ACCEPT_LANGUAGES’] = “en-US,en;q=0.8”;
$lang_parts = Array(‘en-Us’,‘en;q=0.8’);
$lang_parts[0] = ‘en-Us’;
substr($lang_parts[0],0,2) = ‘en’;

Great thanks!

Sponsor our Newsletter | Privacy Policy | Terms of Service