自动检测语言并重定向用户


Auto detect language and redirect user

我正在做自己的网站,我设法编写了一些代码,引导用户根据浏览器的语言选择语言版本。这是脚本:

<?php
  if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "sv")
    header("location: index.php");
  if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "pt")
    header("location: pt/index.php");
  else 
    header("location: en/index.html");
?>

我已经把这个放在index.php之前。它似乎起作用了,因为我不在英语国家,但我的浏览器是英语的,我被重定向到英语版本。

这是正确的吗?有更好/更干净的方法吗?

PHP 5.3.0+附带locale_accept_from_http(),它从Accept-Language标头中获取首选语言。

与自写方法相比,您应该始终更喜欢此方法,因为标头字段比您想象的要复杂。(这是一个加权偏好列表。)

你应该检索这样的语言:

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

但即便如此,您也不会只为每个英语用户提供en,为西班牙语用户提供es。它可能会变得比这困难得多,像es-ESes-US这样的东西是标准的。

这意味着您应该迭代正则表达式的列表,并尝试以这种方式确定页面语言。有关示例,请参阅PHP-I18N。

好吧,我的代码遇到了一些问题,这并不奇怪,因为我不是PHP专家。因此,我一直在寻找可能的解决方案,并在另一个网站上找到了以下代码:

<?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 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 == "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();
}
?>

这做得很完美!我只剩下一个问题了。即使直接链接到另一种语言,也无法更改语言,因为一旦加载页面,php块就会将我重定向到borwser的语言。如果你生活在另一个国家,母语是瑞典语,但你的浏览器是英文的,因为你在英国买了电脑,这可能是一个问题。

因此,我对这个问题的解决方案是为每种语言(甚至是主语言)创建一个重复版本的文件夹,而在index.html上没有这个php代码(因此不是index.php)。所以现在我的网站正在自动检测语言,用户也可以选择手动更改它,以防他们想要!

希望它能帮助其他有同样问题的人!

我认为你的想法很棒。可能是帮你最短的代码:

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

这应该可以正常工作。您也可以使用http_negotiate_language并在此处讨论

最有用的这个代码

    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if(file_exists('system/lang/'.$lang.'.php'))
{
    include('system/lang/'.$lang.'.php');
}else{
    include('system/lang/en.php'); //set default lang here if not exists translated language in ur system
    }