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?
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.
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.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With