Detect the language of anonymous users

From PunBB Resource Wiki

Jump to: navigation, search

If you have a multilingual installation of PunBB, you can make the forum appear in the preferred language of users even if they are not logged in, by using the HTTP Accept-Language header.

This is a mod for punbb 1.2.10+. Here is an example for a Swedish/Dutch forum (sv/nl). If the user does not accept either Swedish or Dutch, it will fall back to the default.

First add this function to include/functions.php (modify for your own set of languages):

// use User-Agent language to determine language for guests
// arg is associative array, sets ['language'], uses ['g_id']
// Mod by Han-Kwang Nienhuys, 2006-2007
function set_guest_lang(&$pun_user)
{
  if ($pun_user['g_id'] != PUN_GUEST)
    return;
  if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
    return;
  $acclang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  $lang = $pun_user['language'];
  if (preg_match('/sv.+nl/', $acclang)) { // prefer sv above nl
    $lang = 'Svenska';
  } else if (preg_match('/nl.+sv/', $acclang)) { // prefer nl above sv
    $lang = 'Nederlands';
  } else if (preg_match('/sv/', $acclang)) { // knows sv, not nl
    $lang = 'Svenska';
  } else if (preg_match('/nl/', $acclang)) { // knows nl, not sv
    $lang = 'Nederlands';
  }
  $pun_user['language'] = $lang;
}

And then find this in include/common.php :

// Check/update/set cookie and fetch user info
$pun_user = array();
check_cookie($pun_user);

And add this below it:

set_guest_lang($pun_user);

See also

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox