1

オンラインでいくつかのことを読んだ後、ブラウザの言語を検出し、ユーザーを正しい Web サイトのバージョンにリダイレクトするこの PHP スクリプトを思いつきました。Short 氏は、ユーザーがスウェーデン語のブラウザーを使用している場合、スクリプトは index.php にリダイレクトする必要があり、そうでない場合はユーザーを en.php にリダイレクトする必要があると述べました。

一部のコンピューターや携帯電話では正常に機能し、他のコンピューターや携帯電話では Web サイトをブロックします。スクリプトに問題があり、古いブラウザで競合が発生していると思います。

それで、私のスクリプトを見て、私が何か間違ったことをしていないか、どうすれば修正できるか教えていただけますか?

乾杯!

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

PS - はい、スクリプトはタグの前にあり、「?>」タグとタグの間にスペースはありません。

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"が、3 番目のケースを忘れていました$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 に答える