php redirect based on browser language

Status
Not open for further replies.

Cormac

New Member
Hi guys,
I have the following script which should redirect a user if they are using a Polish browser to a specific page. I have asked a Polish friend to test it using his Polish version of Firefox but he said he didn't work. Here is the code:

PHP:
<? 
function redirect()
  {
  $lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

    switch($lang){
        case 'pl':
            $redir_url = "http://www.google.pl";
            break;
        default:
        case 'en':
            $redir_url = "http://www.allotherbrowsers.com/landingpage.php";
            break;
    }
    header("Location: $redir_url");
}
redirect();


?>
He says he gets brought to allotherbrowsers.com/landingpage.php instead of google.pl

Can anyone spot the problem?
 

louie

New Member
did you try echo the result to see what's going on?
PHP:
function redirect()
  {
  $lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
echo $lang; exit();//comment this when finished
 
    switch($lang){
        case 'pl':
            $redir_url = "http://www.google.pl";
            break;
        default:
        case 'en':
            $redir_url = "http://www.allotherbrowsers.com/landingpage.php";
            break;
    }
    header("Location: $redir_url");
}
redirect();
 

Cormac

New Member
the echoed result is - pl,en-us;q=0.7,en;q=0.3

That agent seems a bit odd. I downloaded the Polish version of Firefox myself to test. I opened a browser-language.php file in the browser and it displayed the following information - Mozilla/5.0 (Macintosh; U; Intel Mac OS X; pl; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13

I'm stumped! :(
 

Cormac

New Member
I tired some alternative code and it works:
PHP:
<?php 
$lang = ($_SERVER['HTTP_ACCEPT_LANGUAGE']); 

if(ereg("pl", $lang)) { 
    header("location: http://google.pl"); 
} else { 
    header("location: http://google.com"); 
} 
?>
 

louie

New Member
of course it does because ereg looks for the match (in this case "pl") and if found returns true.
You can also use preg_match which is faster as it's Perl-compatible.
 
Status
Not open for further replies.
Top