Skip to content
Advertisement

PHP- Get current locale

I am setting the locale of the website using this function:

function set_locale($locale) { // ie. en, es

    $language = $locale;
    putenv("LANG=".$language); 
    setlocale(LC_ALL, $language);
    $domain = "phd";
    bindtextdomain($domain, "locale"); 
    bind_textdomain_codeset($domain, 'UTF-8');

    textdomain($domain);

} // end set_locale

When someone visits the site, they have the ability to change their locale. What I am trying to do is somewhere else in the site retrieve what the current locale is.

How would I do this?

Advertisement

Answer

You can call setlocale like so, and it’ll return the current local.

$currentLocale = setlocale(LC_ALL, 0);
echo $currentLocale; //outputs C/en_US.UTF-8/C/C/C/C on my machine

Here is documentation from php.net as commented by @JROB

locale

If locale is “0”, the locale setting is not affected, only the current setting is returned.

If locale is NULL or the empty string “”, the locale names will be set from the values of environment variables with the same names as the above categories, or from “LANG”.

If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement