Search code examples
phpinternationalizationlocale

How do I automatically set a user's locale in PHP?


Is there an easy way to parse the user's HTTP_ACCEPT_LANGUAGE and set the locale in PHP?

I know the Zend framework has a method to do this, but I'd rather not install the whole framework just to use that one bit of functionality.

The PEAR I18Nv2 package is in beta and hasn't been changed for almost three years, so I'd rather not use that if possible.

Also nice would be if it could figure out if the server was running on Windows or not, since Windows's locale strings are different from the rest of the world's... (German is "deu" or "german" instead of "de".)


Solution

  • Nice solution is on its way.

    Without that you'll need to parse that header. It's a comma-separated list of semicolon-separated locales and attributes.

    It can look like this:

    en_US, en;q=0.8, fr_CA;q=0.2, *;q=0.1
    

    and then try each locale until setlocale() accepts it. Be prepared that none of them may match.

    Don't base on it anything too important or allow users to override it, because some users may have misconfigured browsers.


    For Windows locale, perhaps you need to convert ISO 639-1 names to ISO 639-2/3?