Skip to content
Related Articles

Related Articles

Improve Article
How to detect Browser Language in PHP?
  • Last Updated : 17 Feb, 2020

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-






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

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.




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

The above program will redirect to links like

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