PHP语言检测脚本

时间:2014-03-20 15:25:49

标签: php html5 detection spoken-language

在我在线阅读了一些内容之后,我想出了这个PHP脚本来检测浏览器的语言,并将用户重定向到正确的网站版本。 Short说,如果用户有一个瑞典语浏览器,那么脚本应该重定向到index.php,如果没有,那么它应该将用户重定向到en.php。

它在某些计算机和手机中运行良好,而在其他计算机和手机中它会阻止网站。我认为脚本不正常并且在旧版浏览器中引起了一些冲突。

那么,请你看看我的剧本并告诉我,如果我做错了什么,我该如何解决?

干杯!

<?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。 - 是的,脚本在标签之前,“?&gt;”之间没有空格标签和标签。

1 个答案:

答案 0 :(得分: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();
}
?>

btw header("location: ...");需要像header("location:http://www.domain.com/en.php");这样的绝对URI(某些客户端也接受相对URI)