wordwannabe
wordwannabe

Reputation: 101

how to get current locale in PHP

I would like to get the current system locale of a server (say windows 7 os). This is to ensure that different language setting uses different parts of code in PHP.
However, I could not find any API that does this.
Can anyone tell me the name of the function?

Upvotes: 3

Views: 3456

Answers (3)

ADJenks
ADJenks

Reputation: 3414

Oddly, you get the locale for the PHP process by using the setlocale function like so:

setlocale (LC_ALL,"0");

The second parameter is "locales" and it says in the docs:

If locales is "0", the locale setting is not affected, only the current setting is returned.

So it always returns the locale, but you can tell it to set nothing and just return the current locale.

Note: This isn't the system locale, but the locale of the PHP process itself, which is usually derived from the system locale, but may be different if you previously called setlocale and changed it. I thought at first that that's what this question was looking for, but I think the answer from Gags is more correct, calling "locale -a" with "exec()" to get the actual system language independent of the PHP process.

Upvotes: 1

Aiken
Aiken

Reputation: 272

Best answer above from Gags. If you want the contents of the accept-language: header from the current request, if there is one, use:

$_SERVER['HTTP_ACCEPT_LANGUAGE']

Upvotes: 0

Gags
Gags

Reputation: 3829

Having thought more about the problem and the particular setup I have, I came up with this solution, which seems to work. Note that I don't have control over what languages I need to support: there are translation files dropped into a predefined place and system locales installed by someone else. During runtime, I need to support a particular language if corresponding translation file exists and and system locale is installed. This got me to this solution:

Use below function

function getLocale($lang)
{
    $locs = array();
    exec('locale -a', $locs);

    $locale = 'en-IN';
    foreach($locs as $l)
    {
        $regex = "/$lang\_[A-Z]{2}$/";
        if(preg_match($regex, $l) && file_exists(TRANSROOT . "/$lang.php"))
        {
            $locale = $l;
            break;
        }
    }

    return $locale;
}

I'm defaulting to en-IN if I cannot resolve a locale, because I know for certain that en-IN is installed.

Upvotes: 1

Related Questions