Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to detect client locale in PHP

Tags:

php

locale

I would like to be able to detect what country a visitor is from on my website, using PHP.

Please note that I'm not trying to use this as a security measure or for anything important, just changing the spelling of some words (Americans seems to believe that the word "enrolment" has 2 Ls.... crazy yanks), and perhaps to give a default option in a "Select your country" list.

As such, using a Geolocation database is a tad over-the-top and I really don't want to muck about with installing new PHP libraries just for this, so what's the easiest/simplest way to find what country a visitor is from?

like image 450
nickf Avatar asked Nov 18 '08 01:11

nickf


People also ask

How do I find user locale?

To get the user's locale in the browser, access the first element of the languages property on the navigator object, e.g. navigator. languages[0] . The property returns an array of strings that represent the user's preferred languages.

How is locale determined?

A locale is a location-based language setting that determines which conversational settings and strings to display. The user specifies their locale using settings on their device. They may change this setting whenever they wish, including during a conversation with a Business Messages agent.

How can I get Lang in PHP?

We can use HTTP_ACCEPT_LANGUAGE key to get the language of the browser. echo substr ( $_SERVER [ 'HTTP_ACCEPT_LANGUAGE' ], 0, 2); ?> You can test it by changing your browser's language.

What is locale PHP?

Locale information is language, monetary, time and other information specific for a geographical area. Note: The setlocale() function changes the locale only for the current script. Tip: The locale information can be set to system default with setlocale(LC_ALL,NULL)


1 Answers

PHP provides a function since 5.3.0 to parse the $_SERVER['HTTP_ACCEPT_LANGUAGE'] variable into a locale.

$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); echo $locale; // returns "en_US" 

Documentation: https://www.php.net/manual/en/locale.acceptfromhttp.php

like image 131
Trevor Goodyear Avatar answered Sep 25 '22 20:09

Trevor Goodyear