views:

61

answers:

1

This tutorial is about language selection according to preferred language on browser.

lang.php:

<?php

function dlang($Var)
{
 if(empty($GLOBALS[$Var]))
 {
  $GLOBALS[$Var]=(!empty($GLOBALS['_SERVER'][$Var]))?
  $GLOBALS['_SERVER'][$Var]:
  (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var]))?
  $GLOBALS['HTTP_SERVER_VARS'][$Var]:'';
 }
}

function language()
{
 // Detect HTTP_ACCEPT_LANGUAGE & HTTP_USER_AGENT.
 dlang('HTTP_ACCEPT_LANGUAGE');
 dlang('HTTP_USER_AGENT');

 $_AL=strtolower($GLOBALS['HTTP_ACCEPT_LANGUAGE']);
 $_UA=strtolower($GLOBALS['HTTP_USER_AGENT']);

 // Try to detect Primary language if several languages are accepted.
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(strpos($_AL, $K)===0)
   return $K;
 }

 // Try to detect any language if not yet detected.
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(strpos($_AL, $K)!==false)
   return $K;
 }
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(preg_match("/[\[\( ]{$K}[;,_\-\)]/",$_UA))
   return $K;
 }

 // Return default language if language is not yet detected.
 return $GLOBALS['_DLANG'];
}

// Define default language.
$GLOBALS['_DLANG']='es';

// Define all available languages.
// WARNING: uncomment all available languages

$GLOBALS['_LANG'] = array(
'es',
'en',
'zh'
);
?>

session.php:

<?php
//proc all page display
include('lang.php'); //language detector
class Session
{
 var $lang;         //Username given on sign-up
 var $url;          //The page url current being viewed
    var $referrer;     //Last recorded site page viewed

 /* Class constructor */
   function Session(){
      $this->time = time();
      $this->startSession();
   }

   function cf($filename){//function to clean a filename string so it is a valid filename
     $fp = explode('/',$filename);
  $num = count($fp);
  return $fp[$num-1];
 }

   /**
    * startSession - Performs all the actions necessary to 
    * initialize this session object. Tries to determine if the
    * the user has logged in already, and sets the variables 
    * accordingly. Also takes advantage of this page load to
    * update the active visitors tables.
    */
   function startSession(){
     session_start();   //Tell PHP to start the session

  /* Set referrer page */
      if(isset($_SESSION['url'])){
         $this->referrer = $search = $this->cf($_SESSION['url']);
      }else{
         $this->referrer = "/";
      }

      /* Set current url */
      $this->url = $_SESSION['url'] = $this->cf($_SERVER['PHP_SELF']);

   /* Set user-determined language: */
    //set up languages array:
    $langs = array('en','es','zh');
  //
   if(isset($_GET['lang'])){
    if(in_array($_GET['lang'],$langs)){
   $this->lang =  $_SESSION['lang'] = $_GET['lang'];
  }
   }
   if(!isset($_SESSION['lang']) || !in_array($_SESSION['lang'],$langs)){
      $this->lang = $_SESSION['lang'] = language();
   }
 }
};
/**
 * Initialize session object - This must be initialized before
 * the form object because the form uses session variables,
 * which cannot be accessed unless the session has started.
 */
$session = new Session;
?>

Now I want to choose a lang.en.php or a lang.es.php according to the value of $lang (en, es, etc...). I want each language's content to have its own file.

I think this code might work:

// 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';
}

 include_once 'languages/'.$lang_file;
?>

lang.en.php (sample):

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

I placed that switch statement at the end of the session.php file, but no matter what I do, its stuck displaying the default language (en).

Any suggestions?

+1  A: 

Try echoing $lang and seeing what its value is -- so you could see if that's the problem first? Also, I suggest you replace the switch with a plain

include_once("languages/lang.$lang.php");

If you want to check if it's a valid language you could compare it against and array or check if the file exists first.

henasraf
@henasraf I did echo $lang and its value is Array
janoChen
@henasraf I did var_dump($lang) and its value was NULL
janoChen
$lang only exists in the class context -- if checking the $lang is within the class, shouldn't you be accessing it as $this->lang? Unless there's code binding $lang to your $session->lang in which case I'd want to see it cause something might be messing up on that way
henasraf
@henasrf I did: var_dump($session) and it displayed: object(Session)#1 (4) { ["lang"]=> NULL ["url"]=> string(9) "index.php" ["referrer"]=> string(9) "index.php" ["time"]=> int(1267349689) }
janoChen
@henasrf and $_SESSION[lang] = en
janoChen
see my comment on the OP's post: always use whitelisting when possible (`in_array` in this case)
knittl
@knittl, never mind I made the code work. I placed the switch statements in a file called localization.php and it works perfectly (using switch('$_SESSION[lang]').But I can't do: include 'languages/lang.'.$_SESSION[lang].'.php';Dunno why.
janoChen
@janochen because it is `$_SESSION['lang']` and not `$_SESSION[lang]`
knittl
@knittl sorry I made a typo here, but in the actual code I wrote: if(in_array($lang, $GLOBALS[_LANG])) include 'languages/lang.'.$_SESSION['lang'].'.php';and it didn't work.
janoChen
Again, you're looking for `$GLOBALS['_LANG']`, not `$GLOBALS[_LANG]`.
henasraf
@knittl I had: if(in_array($lang, $GLOBALS['_LANG'])) include 'languages/lang.'.$_SESSION['lang'].'.php';and still not working.
janoChen