How can I display a language according to the user's browser's language inside this code?

Posted by janoChen on Stack Overflow See other posts from Stack Overflow or by janoChen
Published on 2010-02-27T12:02:57Z Indexed on 2010/04/25 4:23 UTC
Read the original article Hit count: 402

Filed under:
|
|

How can I display a language according to the user's browser's language inside this mini-framework for my multilingual website?

Basically, it has to display the default language of the user if there's no cookies.

Example of index.php: (rendered output)

<h2><?php echo l('tagline_h2'); ?></h2>

common.php: (controller of which language to output)

<?php
session_start();
header('Cache-control: private'); // IE 6 FIX

if(isSet($_GET['lang']))
{
$lang = $_GET['lang'];

// register the session and set the cookie
$_SESSION['lang'] = $lang;

setcookie("lang", $lang, time() + (3600 * 24 * 30));
}
else if(isSet($_SESSION['lang']))
{
$lang = $_SESSION['lang'];
}
else if(isSet($_COOKIE['lang']))
{
$lang = $_COOKIE['lang'];
}
else
{
$lang = 'en';
}

//use appropiate lang.xx.php file according to the value of the $lang
switch ($lang) {
  case 'en':
  $lang_file = 'lang.en.php';
  break;

  case 'es':
  $lang_file = 'lang.es.php';
  break;

  case 'tw':
  $lang_file = 'lang.tw.php';
  break;

  case 'cn':
  $lang_file = 'lang.cn.php';
  break;

  default:
  $lang_file = 'lang.en.php';
}

//translation helper function
function l($translation) {
 global $lang;
 return $lang[$translation]; }

include_once 'languages/'.$lang_file;
?>

Example of /languages/lang.en.php: (where multilingual content is being stored)

<?php
$lang = array(
 'tagline_h2' => '...',

© Stack Overflow or respective owner

Related posts about php

Related posts about browser