Last updated on November 13th, 2024 at 10:17 am

This tutorial presents a script designed to identify the language settings of a user’s browser and subsequently redirect them to a page tailored for their specific language or location. For websites that support multiple languages, this script comes handy as it allows for the detection of the browser’s language, enabling the appropriate language version of the webpage to be displayed to the user.

This PHP code snippet can be used to detect the user’s browser language and then redirect to another page (language.php) while passing the detected language as a query parameter.

$language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
echo "The browser language is ".$language;
header('Location:language.php?lang=$language');

$_SERVER['HTTP_ACCEPT_LANGUAGE']: This is a PHP superglobal variable that retrieves the Accept-Language HTTP header sent by the user’s browser. This header indicates the user’s preferred languages and regional settings (e.g., en-US, fr, es).

substr(..., 0, 2): The substr function is used to get a substring of the first two characters from $_SERVER['HTTP_ACCEPT_LANGUAGE']. This assumes that the first two characters represent the primary language code (e.g., en for English, fr for French).

$language: The result is stored in $language, which now holds a two-character language code.

header('Location: ...'): This PHP function sends an HTTP header to the client, instructing the browser to redirect to a new URL.

URL with Query Parameter: 'Location: language.php?lang=$language' attempts to pass $language as a query parameter (lang) to language.php.