We can detect requesting browser’s language using PHP’s super global variable
$_SERVER. It is a superglobal variable which holds information about headers, paths, and script locations. It is basically an associative array in PHP which has keys like
SERVER_NAME, SERVER_ADDR, REQUEST_METHOD, etc.
We can use
HTTP_ACCEPT_LANGUAGE key to get the language of the browser.
We can see an output like:
en-US, en;q=0.9, hi;q=0.8, fr;q=0.7
In order to get the current language of the browser, we can use PHP’s built-in substr function to get the first two letters of the string like-
After running the above program you’ll see the output as your current browser’s language –
You can test it by changing your browser’s language. If you are on chrome you can go to
chrome://settings/languages and choose a different language.
Now run the above program again and you’ll see the output as the newly chosen language.
Example 2: If your website has different pages for different languages, you can use this method in order to redirect to the page according to the user’s browser’s language.
The above program will redirect to links like