Detect a user’s language and region in PHP

When a user opens the homepage of an international site, it should propose localized content matching its language and area.

This post describes how to detect a user’s language and region in PHP.

Prerequisites

The locales

The locales are predefined values corresponding to a language and a region.

For example:

en_US for english in the United States
fr_FR for french in France
fr_CA for french in Canada

The locales allow to handle localized content (translations, formatted dates, numeric and monetary formats…).

Detect a user’s locale

The list of a user’s preferred locales is provided by its browser in $ _SERVER [‘HTTP_ACCEPT_LANGUAGE’].

function DetectLocale() {
    $Language = str_replace('-', '_', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    if (preg_match('/[a-z]{2}_[A-Z]{2}/', $Language, $MatchesArray)) {
        return $MatchesArray[0];  // Preferred locale
    }
    return 'en_US';  // Default locale
}

Once the locale detected, it is possible to:

  • Keep locale in a cookie with the setcookie function.
  • Redirect the user to a localized part of the site with the header function. For example header(‘Location: http://en-us.mydomain.com’); or header(‘Location: http://mydomain.com/en-us/’);
  • Set the locale used by PHP with the setlocale function.
  • Show formatted dates with the strftime function.
  • Obtain localized information about numeric and monetary formats with the localeconv function.

Leave a Reply

Your email address will not be published. Required fields are marked *

*