0

I am trying to do localization for a site I'm working on at the moment and am doing something like this:

if(!isset($_SESSION['lang'])){
    $_SESSION['lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}else if(isset($_GET['lang']) && !empty($_GET['lang'])){
    $_SESSION['lang'] = $_GET['lang'];
}

This is fine and works as expected, however, sometimes there is no value for $_SERVER['HTTP_ACCEPT_LANGUAGE'], after a quick test of visitors to our site approximately 20% actually have a value and 80% do not.

Is there a better way to detect a user's language?

halfer
  • 19,824
  • 17
  • 99
  • 186
Paddy Hallihan
  • 1,624
  • 3
  • 27
  • 76
  • Just fallback to `en`, in an `else` block. – Lawrence Cherone Aug 31 '18 at 11:26
  • You could get the user's IP address and use it to parse the country the user is at. – Phiter Aug 31 '18 at 11:27
  • @Phiter Unless they are hiding in an Onion :) – RiggsFolly Aug 31 '18 at 11:31
  • @LawrenceCherone thanks for your comment I'm defaulting back to english in my translation function anyway – Paddy Hallihan Aug 31 '18 at 11:31
  • @RiggsFolly yeah if I couldn't track the IP address I'd just fallback to good old english. – Phiter Aug 31 '18 at 11:32
  • Maybe worth you [reading this](https://stackoverflow.com/questions/673905/best-way-to-determine-users-locale-within-browser) – RiggsFolly Aug 31 '18 at 11:33
  • @Phiter yeah was thinking that but after testing a bit the 20% i mentioned above actually confused me, like i've users in the states using french and german and users in germany using english etc – Paddy Hallihan Aug 31 '18 at 11:34
  • @RiggsFolly thanks for that link will look into this and see how I get on – Paddy Hallihan Aug 31 '18 at 11:35
  • Well I live in Brazil and I use google in English. Google always goes back to Portuguese some times. It's weird – Phiter Aug 31 '18 at 11:35
  • @phiter, yeah was trying to read up on how this is actually set, like a user can set their language for their system and browser seperately and if the browser is not set does it just pick up the system or how does it actually work – Paddy Hallihan Aug 31 '18 at 11:39
  • Found this https://superuser.com/questions/1263533/how-is-serverhttp-accept-language-computed but it's not exactly helpful – Paddy Hallihan Aug 31 '18 at 11:41
  • one more https://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference – ino Aug 31 '18 at 12:47

1 Answers1

0

As suggested I ended up falling back to English in an else statement if I cannot determine the language

Paddy Hallihan
  • 1,624
  • 3
  • 27
  • 76