How to detect Browser Language in PHP?

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.

Syntax:

$_SERVER['HTTP_ACCEPT_LANGUAGE']

We can see an output like:

en-US, en;q=0.9, hi;q=0.8, fr;q=0.7

Example 1:
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-



filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
   echo substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
  
?>

chevron_right


After running the above program you’ll see the output as your current browser’s language –

en

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
   $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
  
   // Redirect browser 
   header("Location: https://www.geeksforgeeks.org/" . $lang . "/index.php");    
   exit;
  
?>

chevron_right


The above program will redirect to links like

http://www.example.com/en/index.php
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.