1

After I read some stuff on-line I came up with this PHP script to detect the browser's language and redirect the user to the correct website's version. Short said, if the user has a browser in Swedish, then the script should redirect to index.php, if not, then it should redirect the user to en.php.

It works fine in some computers and mobile phones and in others it blocks the website. I suppose that the script is not OK and is causing some conflict in older browsers.

So, could you please take a look at my script and tell me if I am doing anything wrong and how can I fix it?

Cheers!

<?php
include ('administration/fonts.php');
?><?php
$lc = ""; // Initialize the language code variable
// Check to see that the global language server variable isset()
// If it is set, we cut the first two characters from that string
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
    $lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
// Now we simply evaluate that variable to detect specific languages

if($lc == "sv"){
    header("location: index.php");
    exit();
}

else if($lc == "en"){
    header("location: en.php");
    exit();
}
?>

P.S. - Yes, the script is before the tag and there are no spaces between the "?>" tag and tag.

4

1 回答 1

2

从 OP 添加详细信息后的新答案。

英语用户应该被重定向,但瑞典用户应该留在这个网站上,所以我们将这样重写代码(我添加了注释// Reeno):

<?php
include ('administration/fonts.php');

$lc = ""; // Initialize the language code variable
// Check to see that the global language server variable isset()
// If it is set, we cut the first two characters from that string
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
    // Reeno: I added strtolower() if some browser sends upper case letters
    $lc = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
}
// Now we simply evaluate that variable to detect specific languages

// Reeno: Redirect all non-Swedish users to the English page (they can have "en", but also "dk", "de", "fr"...
if($lc != "sv"){
    header("location: http://www.domain.com/en.php");
    exit();
}
// Reeno: Swedish users stay on this site
?>
HTML code...

旧答案

您检查$lc == "sv"$lc == "en"忘记了第三种情况:$lc可能是空的!

像这样重写最后的 if,这样每个使用非瑞典语浏览器的人都会得到en.php

if($lc == "sv"){
    header("location: index.php");
    exit();
}
else {
    header("location: en.php");
    exit();
}
?>

顺便说一句header("location: ...");,需要一个绝对 URI header("location:http://www.domain.com/en.php");(某些客户端也接受相对 URI)

于 2014-03-20T15:28:13.663 回答