Language
Category
Search

Detect the language used in the user's browser using PHP

How to get the browser language in PHP and how to use this information to create a script that receives this value if no language is configured

Detect the language used in the user's browser using PHP
At PHP By Rudi Drusian
Published on
Last updated

It is possible to know which language is currently defined in the user's browser using the PHP super global variable $_SERVER, consulting the 'HTTP_ACCEPT_LANGUAGE' index.

PHP

<?php
   echo $_SERVER['HTTP_ACCEPT_LANGUAGE'];
   # Expected something like: en,pt-BR;q=0.5
?>

To get only the part that matters, which are the first two letters:

PHP

<?php
   echo substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)
   # Expected something like: en
?>

To create a PHP script in which the user can define the language through a form using a GET request and if no language is chosen, the current language of the browser is used as long as it is in a list of predetermined languages.

PHP

<?php
   if (isset($_GET['lang'])) {
      $lang = $_GET['lang'];
   } else {
      $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
   }
   if (!in_array($lang, array("en","pt","es"))) $lang = "en";
?>

The in_array function in this script checks if the language is among those configured in the array (en, pt, es), that is, English, Portuguese or Spanish, and if it does not find the language, it sets it to English (en). This guarantees that the $lang variable will always have a valid and expected value.

References

This is not my original language and I don't speak it very well. I used my little knowledge and translators tools to compose the text of this article. Sorry for possible spelling or grammatical errors, suggestions for corrections are appreciated and can be sent to the contact email in the footer of the site. My intention is to share some knowledge and I hope this translation is good enough.