PHP检测用户语言[关闭]

I need a script like

if ($userLanguage === 'english') {
  echo "we have detected you are English. would you like to visit our site in English?";
} else {
  header('location: /index.php?lang=default');
}

The script above is used for an example. I have looked all over google and all it gave me was geolocation scripts and such. I don't want a third party URL in my script. You never know if their service goes down or not.

Where do I find something like this?

I'm not going to repeat all the valid answers here, but this link shows another good approach (for multi-lingo websites) taking advantage of http_negotiate_language() method mirror

So combining that mapping and your exciting code you will have:

$map = array("en" => "english", "es" => "spanish");
$userLanguage = $map[ http_negotiate_language(array_keys($map)) ];

if ($userLanguage === 'english') {
  echo "we have detected you are English. would you like to visit our site in English?";
} else {
  header('location: /index.php?lang=default');
}

But if you are only interested to detect the english (en) language, you might want to shorten the script to:

if ('en' == substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)) {
  echo "we have detected you are English. would you like to visit our site in English?";
} else {
  header('location: /index.php?lang=default');
}

i would do something like this:

<?php
$language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($language){
    case "sv":
        include("index_swedish.php");
        break;
    case "nl":
        include("index_dutch.php");
        break; 
    default:
        include("index_english.php"); // or do what ever you want
        break;

}
?>

Here is a list of browser language codes

yes the idea is good, try the short one also,

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
header("location: ".$lang."/index.php");
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if ($lang == 'en') {
 echo "we have detected you are English. would you like to visit our site in English?";
} 
else {
  header("location: /index.php?lang=default");
}