Menü schliessen
Created: November 21st 2023
Last updated: March 16th 2024
Categories: Common Web Development,  Php,  Wordpress
Author: Tim Fürer

PHP: How to find out client browser language

Tags:  function,  guide,  PHP,  wordpress
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

The ability to ascertain the preferred language of the user is helpful for creating user-friendly experiences. Here's a function that lets you determine what language the user's browser prefers.


Helper Function

<?php

function get_client_lang() {
    $client_lang = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE'])[0];

    if (strpos($client_lang, '-') !== false) {
        $client_lang = explode('-', $client_lang)[0];
    }

    return strtolower($client_lang);
}

?>

This function, named get_client_lang(), operates by accessing the $_SERVER['HTTP_ACCEPT_LANGUAGE'] superglobal array, which stores the language preferences transmitted by the client's browser. Here's a technical breakdown of its functionality:

  1. It extracts the accepted languages from the browser as a string.
  2. The string is split by commas to isolate the first language preference.
  3. If the selected language contains a region code, such as 'en-US', it further parses the string to retain only the language code (e.g., 'en').
  4. The standardized and lowercase language code is then returned.