Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 PHPintlextension to be installed. You can install it usingsudo apt-get install php-intlon 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.
