Simplest way to detect client locale in PHP

PHP provides a function beginning from 5.3.0 to parse the $_SERVER['HTTP_ACCEPT_LANGUAGE'] variable into a locale using the Locale::acceptFromHttp() method.

Note: This requires the PHP intl extension to be installed. You can install it using sudo apt-get install php-intl on Ubuntu/Debian systems.

Example

The following example shows how to detect client locale ?

<?php
    $locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
    echo $locale;
?>

Output

This will produce the following output ?

en_US

How It Works

The $_SERVER['HTTP_ACCEPT_LANGUAGE'] variable contains the Accept-Language HTTP header sent by the client's browser. Most browsers submit this header based on the user's system locale settings.

Common examples include:

  • en-us ? for US English users
  • en-gb ? for UK English users
  • en-za ? for South African English users
  • fr-fr ? for French users

Some older browsers may only send en without the country code.

Alternative Method

You can also manually parse the header if the intl extension is not available ?

<?php
    $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    echo "Detected language: " . $lang;
?>

Conclusion

Using Locale::acceptFromHttp() is the most reliable way to detect client locale in PHP. This method is more accurate than geo-IP based guessing and respects the user's actual language preferences.

Updated on: 2026-03-15T08:43:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements