Simplest way to detect client locale in PHP

nickf picture nickf · Nov 18, 2008 · Viewed 54.3k times · Source

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?

Answer

Trevor Goodyear picture Trevor Goodyear · Mar 11, 2014

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