2

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?

4 Answers4

3

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');
}
brasofilo
  • 25,496
  • 15
  • 91
  • 179
Ali
  • 2,993
  • 3
  • 19
  • 42
  • Strangely enough, the php.net documentation for `http_negotiate_language()` doesn't exist anymore. Haven't researched the *why* – brasofilo Nov 09 '17 at 16:31
0

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

NorthernLights
  • 370
  • 3
  • 16
  • That http header might contain more than a single language. – arkascha Jul 13 '15 at 17:45
  • Change of plans, is it possible to detect if the user is not from netherlands (NL)? E.g. if you're german, you will get an popup that you can view the site in English and so on with every country but the netherlands. Is that possible? – Willy Wybert Jul 13 '15 at 18:02
  • Added a default case to the code, it should do what you are looking for. – NorthernLights Jul 13 '15 at 18:07
0

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

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
header("location: ".$lang."/index.php");
0
$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");
}
charlesqwu
  • 354
  • 2
  • 11