CodeIgniter dynamic language functionality - php

I am Codeigniter and i need dynamic language for users.
I have added drop-down at the header and i want to allow users to change language of site at the frontend.
i tried to change language with below code in one controller
$this->config->set_item('language','spanish');
but its not working its not changing language
i also tried with taking session with below code in one of my controller
$mylanguage = $this->session->set_userdata(array('my_language',$dynamiclang));
and tried to access this variable in config file but its also not working.
help me to make this work.

Finally I Got Success to make multi language
follow below steps
MY_Lang.php file in application\core folder
MY_Lang.php
<?php
(defined('BASEPATH')) OR exit('No direct script access allowed');
class MY_Lang extends CI_Lang
{
function __construct() {
global $URI, $CFG, $IN;
$config =& $CFG->config;
$index_page = $config['index_page'];
$lang_ignore = $config['lang_ignore'];
$default_abbr = $config['language_abbr'];
$lang_uri_abbr = $config['lang_uri_abbr'];
#exit('my_lang');
#print_r($URI);
/*if($index_page=='es')
{
#$config['index_page'] = 'es';
#$config['lang_uri_abbr'] = 'es';
#$IN->set_cookie('user_lang', 'es', $config['sess_expiration']);
#$URI->uri_string = str_replace('es','en',$URI->uri_string);
}
else{
#$config['index_page'] = 'en';
#$config['lang_uri_abbr'] = 'en';
#$IN->set_cookie('user_lang', 'en', $config['sess_expiration']);
}
/* get the language abbreviation from uri */
$uri_abbr = $URI->segment(1);
#$uri_abbr='es';
/* adjust the uri string leading slash */
#print $URI->uri_string;
$URI->uri_string = preg_replace("|^\/?|", '/', $URI->uri_string);
if ($lang_ignore) {
if (isset($lang_uri_abbr[$uri_abbr])) {
/* set the language_abbreviation cookie */
$IN->set_cookie('user_lang', $uri_abbr, $config['sess_expiration']);
} else {
/* get the language_abbreviation from cookie */
$lang_abbr = $IN->cookie($config['cookie_prefix'].'user_lang');
}
if (strlen($uri_abbr) == 2) {
/* reset the uri identifier */
$index_page .= empty($index_page) ? '' : '/';
// exit('654');
/* remove the invalid abbreviation */
$URI->uri_string = preg_replace("|^\/?$uri_abbr\/?|", '', $URI->uri_string);
/* redirect */
header('Location: '.$config['base_url'].$index_page.$URI->uri_string);
exit;
}
} else {
/* set the language abbreviation */
$lang_abbr = $uri_abbr;
}
/* check validity against config array */
if (isset($lang_uri_abbr[$lang_abbr])) {
/* reset uri segments and uri string */
//$URI->_reindex_segments(array_shift($URI->segments)); # this is commented becasue this is giving error : #$hok : 09/August/2015
$URI->uri_string = preg_replace("|^\/?$lang_abbr|", '', $URI->uri_string);
/* set config language values to match the user language */
$config['language'] = $lang_uri_abbr[$lang_abbr];
$config['language_abbr'] = $lang_abbr;
/* if abbreviation is not ignored */
if ( ! $lang_ignore) {
/* check and set the uri identifier */
$index_page .= empty($index_page) ? $lang_abbr : "/$lang_abbr";
/* reset the index_page value */
$config['index_page'] = $index_page;
}
/* set the language_abbreviation cookie */
$IN->set_cookie('user_lang', $lang_abbr, $config['sess_expiration']);
} else {
/* if abbreviation is not ignored */
if ( ! $lang_ignore) {
/* check and set the uri identifier to the default value */
$index_page .= empty($index_page) ? $default_abbr : "/$default_abbr";
if (strlen($lang_abbr) == 2) {
/* remove invalid abbreviation */
$URI->uri_string = preg_replace("|^\/?$lang_abbr|", '', $URI->uri_string);
}
/*echo '<pre>';
print_r($_SERVER);
print_r($config['base_url'].$index_page.$URI->uri_string);
exit;*/
$q = $_SERVER['QUERY_STRING'];
if($q)
$q = "/?".$q;
/* redirect */
header('Location: '.$config['base_url'].$index_page.$URI->uri_string.$q);
exit;
}
/* set the language_abbreviation cookie */
$IN->set_cookie('user_lang', $default_abbr, $config['sess_expiration']);
}
log_message('debug', "Language_Identifier Class Initialized");
}
}
/* translate helper */
function t($line) {
global $LANG;
//print_r($LANG);
// exit;
return ($t = $LANG->line($line)) ? $t : $line;
}
function _t($line,$params=array()) {
global $LANG;
if($params){
echo str_replace(array_keys($params),array_values($params),($t = $LANG->line($line)) ? $t : $line);
}
else
echo ($t = $LANG->line($line)) ? $t : $line;
} ?>
and added below things in config.php
$config['language'] = "english";
/* default language abbreviation */
$config['language_abbr'] = "en";
/* set available language abbreviations */
$config['lang_uri_abbr'] = array("en" => "english","es" => "spanish","ca" => "catalan");
/* hide the language segment (use cookie) */
$config['lang_ignore'] = TRUE;
added below code in route.php
$route['^en/(.+)$'] = "$1";
$route['^es/(.+)$'] = "$1";
$route['^ca/(.+)$'] = "$1";
$route['^(\w{2})$'] = $route['default_controller'];
$route['^(\w{2})/(.+)$'] = "$2";
and added language files in language folder like below
language/catalan
language/spanish
language/english
i hope this will help.

Have you tried to add this in Your controller?
$this->load->helper('language');

Load the current language in the cookie and load the language file using the language value in the cookie
Example whenever user selects a language use the function below to set the current language to the cookie
function language($lang = false) {
if($this->input->get('lang')){ $lang = $this->input->get('lang'); }
$folder = 'application/language/';
$languagefiles = scandir($folder);
if(in_array($lang, $languagefiles)){
$cookie = array(
'name' => 'lang',
'value' => $lang,
'expire' => '31536000',
'prefix' => 'my_',
'secure' => false
);
$this->input->set_cookie($cookie);
}
$this->config->set_item('language', $lang);
redirect($_SERVER["HTTP_REFERER"]);
}
Then on the constructor of your main Custom Controller or if you are just extending CI_Controller then load on each controller's constructor the language file(s) and like
$this->lang->load('language_filename', get_cookie('my_lang'));
You are done

Related

CI how to retrieve cookie value in MY_Lang

I've extended the CI_Lang to handle multilanguage.
Now i wanna get the site_lang from the cookie to see if there is already a language chosen
class MY_Lang extends CI_Lang
{
var $currentLanguage;
function __construct() {
global $URI, $CFG, $IN;
$config =& $CFG->config;
/*Get array with available languages*/
$index_page = $config['index_page'];
$default_abbr = $config['lang_abbr'];
$lang_uri_abbr = $config['lang_uri_abbr'];
/* get the language abbreviation from uri */
$uri_abbr = $URI->segment(1);
/* adjust the uri string leading slash */
$URI->uri_string = preg_replace("|^\/?|", '/', $URI->uri_string);
/* get the language_abbreviation from cookie */
$lang_abbr = $IN->cookie('site_lang');
// check validity against config array
if (isset($lang_uri_abbr[$uri_abbr])) {
// reset uri segments and uri string
$URI->segment(array_shift($URI->segments));
$URI->uri_string = preg_replace("|^\/?$uri_abbr|", '', $URI->uri_string);
if(!empty(LOCATION)){
$this->currentLanguage = strtolower('nl');
// set config language values to match the user language
$config['language'] = $this->currentLanguage;
$config['lang_abbr'] = 'nl-be';
}else{
$this->currentLanguage = strtolower($lang_uri_abbr[$uri_abbr]);
// set config language values to match the user language
$config['language'] = $lang_uri_abbr[$uri_abbr];
$config['lang_abbr'] = $uri_abbr;
}
// check and set the uri identifier
$index_page .= empty($index_page) ? $uri_abbr : "/$uri_abbr";
// reset the index_page value
$config['index_page'] = $index_page;
} else {
$config['lang_splash_ignore'] = FALSE;
}
}
now the value of that $lang_abbr is
string '9e25c0674e5616408f3b1fedd0c43243c0e25335dc92962238f6b2d5fcd0ed5b34d78fe5eceef80e447eaef904965f18699a58c082fde710d0e9976afc7373e9RL3VywiN5Ga7GDnac/vhphR+Ls4NnEi6fHZNm0bGrsQ=' (length=172)
The var_dump of $_COOKIE
array (size=4)
'httpTokens' => string 'd18e3a9aff2ee16e7366ac2bf15c7332d1a6afde32ce9db3be4f9193459706feea8925a54ba4369404adbbaf3803e470cd435b3beaf9d8ba3bff9134d351f79f26iSUDpBMwABR6eElE9igxS55I+KEvntC5NgVeQB768=' (length=172)
'httpUser' => string '74f0cc1d2fb1fd22d963bada94a7ea7cd3221cb8f4c023a66cc337986de0f26c87f44c155acb66d9dc56427e762c0b6906650d9e9c56ba83434e89cc06adc8fbNvdll6arPiQsdRJt/yaOL3J+WZWNfizLE9SRQ2KgyNU+qOz9bqPhVLhfB1yEVElXaw9gHoGp6WwqbsbUhH8Ca+g+dIACtHY1fAJUhc0Xpbs=' (length=236)
'ci_session' => string '69efc00e94d5eea572c53070ae32e831395c911e' (length=40)
'site_lang' => string '9e25c0674e5616408f3b1fedd0c43243c0e25335dc92962238f6b2d5fcd0ed5b34d78fe5eceef80e447eaef904965f18699a58c082fde710d0e9976afc7373e9RL3VywiN5Ga7GDnac/vhphR+Ls4NnEi6fHZNm0bGrsQ=' (length=172)
This should normally be 'en' or 'fr' or something.
How can I retrieve that actual value?
EDIT
I do also have my controller extended into MY_Controller:
class MY_Controller extends Auth_Controller
{
var $languages;
var $currentLanguage;
var $currentLanguageAbbr;
var $currentLanguageItem;
/**
* Class constructor
*/
public function __construct()
{
parent::__construct();
$this->is_logged_in();
$this->setCurrentLanguage();
$this->setSubdomainBackgroundColorGlobalVariable();
$this->setSupportedLanguages();
}
public function setCurrentLanguage(){
$ci =& get_instance();
//Get current language from the config
$currentLang = $ci->config->item('language');
$currentLangAbbr = $ci->config->item('lang_abbr');
//Force Dutch when local platform
if(!empty(LOCATION)){
$this->currentLanguage = strtolower('nl');
$this->currentLanguageAbbr = strtolower('nl-be');
}else{
$this->currentLanguage = strtolower($currentLang);
$this->currentLanguageAbbr = strtolower($currentLangAbbr);
}
//Set cookie and session with correct language
$this->session->set_userdata('site_lang', $this->currentLanguage);
$cookie = array(
'name' => 'site_lang',
'value' => $this->currentLanguage,
'expire' => 259200,
'secure' => COOKIE_XSS_FILTERING
);
$this->input->set_cookie($cookie);
defined('CURRENT_LANG') OR define('CURRENT_LANG', $this->currentLanguage);
}

add custom function to Codeigniter config such as site_url() & base_url()

we need to have a new function such as base_url() , named main_site_url() to being able to use it exactly as the same as site_url().
I've just added this to main config file in application/config:
$config['main_site_url'] = 'http//iksna.com/';
and this code to /system/core/config.php
/**
* Main Site URL
* Returns main_site_url . index_page [. uri_string]
*
* #access public
* #param string the URI string
* #return string
*/
function main_site_url($uri = '')
{
if ($uri == '')
{
return $this->slash_item('main_site_url').$this->item('index_page');
}
if ($this->item('enable_query_strings') == FALSE)
{
$suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
return $this->slash_item('main_site_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix;
}
else
{
return $this->slash_item('main_site_url').$this->item('index_page').'?'.$this->_uri_string($uri);
}
}
// -------------------------------------------------------------
but now, it is not accessible by: main_site_url();
is it accessible by: $this->config->main_site_url();
i have this error when is use main_site_url();
error:
Call to undefined function main_site_url()
You can create your own by the following way:
Step 1:
In you application/config/config.php add this, $config['main_site_url'] = 'http//iksna.com/';
Step 2:
In system/core/Config.php add a new function main_site_url() like base_url(), site_url() which are already defined there:
public function main_site_url($uri = '', $protocol = NULL)
{
$main_site_url = $this->slash_item('main_site_url');
if (isset($protocol))
{
if ($protocol === '')
{
$main_site_url = substr($main_site_url, strpos($main_site_url, '//'));
}
else
{
$main_site_url = $protocol.substr($main_site_url, strpos($main_site_url, '://'));
}
}
return $main_site_url.ltrim($this->_uri_string($uri), '/');
}
Step 3:
Now add the following code in system/helpers/url_helper.php
if ( ! function_exists('main_site_url'))
{
function main_site_url($uri = '', $protocol = NULL)
{
return get_instance()->config->main_site_url($uri, $protocol);
}
}
Now you can use main_site_url() anywhere in your controllers, libraries and views just like base_url(), site_url() etc.
Go to
/system/application/libraries
Create one file named
custom_function.php
add function main_site_url inside custom_function.php
call function in controller file using
$this->custom_function->main_site_url();

Kohana 3.3.3 multi language site

I'm new to Kohana, using version 3.3.3.1, I'm trying to build a simple dynamic site with the content/pages stored in mySQL DB. The site should have multiple languages. I tried searching everywhere for a good solution/module but I couldn't find anything that works with latest version of Kohana. I tried also this: https://github.com/shockiii/kohana-multilang but it's not working on the latest kohana.
I want to put the language in URL like this (and possibly hide the parameter for the default language):
http://www.domain.com/topics/page-name-here.html -- this would be default EN
http://www.domain.com/de/test/some-page-name-here.html
http://www.domain.com/fr/category/other-page-name-here.html
In my bootstrap.php I have the following route (before adding the language logic):
Route::set('page', '(<category>)(/<pagename>.html)', array(
'category' => '.*',
'pagename' => '.*'))
->defaults(array(
'controller' => 'Page',
'action' => 'index',
));
I want to have all this multi-language logic inside a module if possible. But I read about overriding the Request, URL, Route, and other classes to be able to do that.
What is the best way I can do this? What should I do/change and where to start?
I know this is more a general question, but any help or guidance is greatly appreciated.
Thanks very much!
1) add <lang> into routes in bootstrap.php:
Route::set('default', '((<lang>)(/)(<controller>)(/<action>(/<id>)))', array('lang' => "({$langs_abr})",'id'=>'.+'))
->defaults(array(
'lang' => $default_lang,
'controller' => 'Welcome',
'action' => 'index',
));
- define $default_lang somehow - I use siteconfig.php file placed inside application/config -see below.
2) Extend/redefine factory method in Request Controller:
<?php defined('SYSPATH') or die('No direct script access.');
class Request extends Kohana_Request {
/**
* Main request singleton instance. If no URI is provided, the URI will
* be automatically detected using PATH_INFO, REQUEST_URI, or PHP_SELF.
*
* #param string URI of the request
* #return Request
*/
public static function factory( $uri = TRUE,$client_params = array(), $allow_external = TRUE, $injected_routes = array())
{
$instance = parent::factory($uri);
$index_page = Kohana::$index_file;
$siteconfig = Model_Siteconfig::load();
$lang_uri_abbr = $siteconfig['lang_uri_abbr'];
$default_lang = $siteconfig['language_abbr'];
$lang_ignore = $siteconfig['lang_ignore'];
$ignore_urls = $siteconfig['ignore_urls'];
/* get the lang_abbr from uri segments */
$segments = explode('/',$instance->detect_uri());
$uri_detection = array_intersect($segments, $ignore_urls);
if(empty($uri_detection))
{
$lang_abbr = isset($segments[1]) ? $segments[1]:'';
/* get current language */
$cur_lang = $instance->param('lang',$default_lang);
/* check for invalid abbreviation */
if( ! isset($lang_uri_abbr[$lang_abbr]))
{
/* check for abbreviation to be ignored */
if ($cur_lang != $lang_ignore) {
/* check and set the default uri identifier */
$index_page .= empty($index_page) ? $default_lang : "/$default_lang";
/* redirect after inserting language id */
header('Location: '.URL::base().$index_page . $instance->detect_uri());
die();
}
}
}
return $instance;
}
}
I use "siteconfig" array with language definitions:
array(
'language_abbr' => 'cs',
'lang_uri_abbr' => array("cs" => "Ĩesky", "en" => "english"),
'lang_ignore' => 'it',
)
3) Extend/redefine "redirect" method in Controller class for automatic language adding:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller extends Kohana_Controller {
/**
* Issues a HTTP redirect.
*
* Proxies to the [HTTP::redirect] method.
*
* #param string $uri URI to redirect to
* #param int $code HTTP Status code to use for the redirect
* #throws HTTP_Exception
*/
public static function redirect($uri = '', $code = 302)
{
$lng = Request::current()->param('lang');
return HTTP::redirect( (string) '/'.$lng.$uri, $code);
}
}
If You would use HTML class (for templates for example), you should probably redefine some other methods like "anchor" for creating anchors with automatic language adding:
<?php defined('SYSPATH') OR die('No direct script access.');
class HTML extends Kohana_HTML {
/**
* Create HTML link anchors. Note that the title is not escaped, to allow
* HTML elements within links (images, etc).
*
* echo HTML::anchor('/user/profile', 'My Profile');
*
* #param string $uri URL or URI string
* #param string $title link text
* #param array $attributes HTML anchor attributes
* #param mixed $protocol protocol to pass to URL::base()
* #param boolean $index include the index page
* #return string
* #uses URL::base
* #uses URL::site
* #uses HTML::attributes
*/
public static function anchor($uri, $title = NULL, array $attributes = NULL, $protocol = NULL, $index = FALSE)
{
//default language
$lng = Request::current()->param('lang');
if ($title === NULL)
{
// Use the URI as the title
$title = $uri;
}
if ($uri === '')
{
// Only use the base URL
$uri = URL::base($protocol, $index).$lng;
}
else
{
if (strpos($uri, '://') !== FALSE)
{
if (HTML::$windowed_urls === TRUE AND empty($attributes['target']))
{
// Make the link open in a new window
$attributes['target'] = '_blank';
}
}
elseif ($uri[0] !== '#')
{
// Make the URI absolute for non-id anchors
$uri = URL::site($lng.$uri, $protocol, $index);
}
}
// Add the sanitized link to the attributes
$attributes['href'] = $uri;
return '<a'.HTML::attributes($attributes).'>'.$title.'</a>';
}
}
I found a great module that is working with Kohana 3.3.3: https://github.com/creatoro/flexilang

Yii and multilingual URLs

I'm trying to create multilingual application. I've implemented ability of translationable content and next step should be showing it to user. I want to have ability of changing language depending on URL. I've found a couple of components for those purposes but they all create urls which I don't like. For example, my application's default language is English and I have content which is translated into French. I have page "contacts", for instance. And URLs which will be generated by application will be: mysite.com/en/contacts, mysite.com/fr/contacts, but I want to have mysite.com/contacts for default language and mysite.com/fr/contacts for French language. It's simillar for site's root too. mysite.com/ - for default language and mysite.com/fr for French.
Is there any methods for implementing these functionality?
I'm using XUrlManager extension XUrlManager on GitHub
Yii generates URL's based on UrlManager rules. If you want URL's without /lang/ code - you need just create correct rules. For example, if you dublicate records in rules array:
'rules'=>array(
'<_c:\w+>/<_a:\w+>'=>'<_c>/<_a>',
'<language:\w{2}>/<_c:\w+>/<_a:\w+>'=>'<_c>/<_a>',
);
your URL's will be generated withou /en/ and /fr/, but URL's with code works too. By default, XUrlManager use previously selected language and store this in session or cookie.
If you want only hide /en/ and use /fr/ and others always, you can change your XUrlManager extension with:
public function createUrl($route,$params=array(),$ampersand='&')
{
if(!isset($params['language']) && Yii::app()->language!=='en')
$params['language']=Yii::app()->language;
return parent::createUrl($route,$params,$ampersand);
}
I've found very elegant method for solving my problem on http://www.elisdn.ru
Reimplement CHttpRequest
class DLanguageHttpRequest extends CHttpRequest
{
private $_requestUri;
public function getRequestUri()
{
if ($this->_requestUri === null)
$this->_requestUri = DMultilangHelper::processLangInUrl(parent::getRequestUri());
return $this->_requestUri;
}
public function getOriginalUrl()
{
return $this->getOriginalRequestUri();
}
public function getOriginalRequestUri()
{
return DMultilangHelper::addLangToUrl($this->getRequestUri());
}
}
Reimplement CUrlManager
class DLanguageUrlManager extends CUrlManager
{
public function createUrl($route, $params=array(), $ampersand='&')
{
$url = parent::createUrl($route, $params, $ampersand);
return DMultilangHelper::addLangToUrl($url);
}
}
Change config
return array(
'sourceLanguage'=>'en',
'language'=>'ru',
'components'=>array(
'request'=>array(
'class'=>'DLanguageHttpRequest',
...
),
'urlManager'=>array(
'class'=>'DLanguageUrlManager',
...
),
),
...
'params'=>array(
'translatedLanguages'=>array(
'ru'=>'Russian',
'en'=>'English',
'de'=>'Deutsch',
),
'defaultLanguage'=>'ru',
),
);
Create DMultilangHelper
class DMultilangHelper
{
public static function enabled()
{
return count(Yii::app()->params['translatedLanguages']) > 1;
}
public static function suffixList()
{
$list = array();
$enabled = self::enabled();
foreach (Yii::app()->params['translatedLanguages'] as $lang => $name)
{
if ($lang === Yii::app()->params['defaultLanguage']) {
$suffix = '';
$list[$suffix] = $enabled ? $name : '';
} else {
$suffix = '_' . $lang;
$list[$suffix] = $name;
}
}
return $list;
}
public static function processLangInUrl($url)
{
if (self::enabled())
{
$domains = explode('/', ltrim($url, '/'));
$isLangExists = in_array($domains[0], array_keys(Yii::app()->params['translatedLanguages']));
$isDefaultLang = $domains[0] == Yii::app()->params['defaultLanguage'];
if ($isLangExists && !$isDefaultLang)
{
$lang = array_shift($domains);
Yii::app()->setLanguage($lang);
}
$url = '/' . implode('/', $domains);
}
return $url;
}
public static function addLangToUrl($url)
if (self::enabled())
{
$domains = explode('/', ltrim($url, '/'));
$isHasLang = in_array($domains[0], array_keys(Yii::app()->params['translatedLanguages']));
$isDefaultLang = Yii::app()->getLanguage() == Yii::app()->params['defaultLanguage'];
if ($isHasLang && $isDefaultLang)
array_shift($domains);
if (!$isHasLang && !$isDefaultLang)
array_unshift($domains, Yii::app()->getLanguage());
$url = '/' . implode('/', $domains);
}
return $url;
}
}
After all of these steps your application will have URLs which you want
More information here

How can I change my multilingual urls from this example.com/index.php?lang=en to this example.com/en/?

Somebody told me that example.com/en is more friendly than example.com/index.php?lang=en.
How can I change my URL last part from ?lang=en to /en/?
(pd: I don't want to use gettext or any framework like zend to accomplish this)
This is how I'm internationalizing and localizing my web page:
(live example: alexchen.co.nr/)
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']='zh-tw';
// Define all available languages.
// WARNING: uncomment all available languages
$GLOBALS['_LANG'] = array(
'en',
'es',
'zh-tw',
'zh-cn'
);
?>
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:
//set cookie
$langs = array('en','es','zh-tw', 'zh-cn');
if(isset($_GET['lang'])){
if(in_array($_GET['lang'],$langs)){
$this->lang = $_SESSION['lang'] = $_GET['lang'];
setcookie("lang", $_SESSION['lang'], time() + (3600 * 24 * 30));
}
}
else if(isSet($_COOKIE['lang'])) {
$_SESSION['lang'] = $_COOKIE['lang'];
}
else {
$_SESSION['lang'] = 'zh-tw';
}
}
};
/**
* Initialize session object - This must be initialized before g
* the form object because the form uses session variables,
* which cannot be accessed unless the session has started.
*/
$session = new Session;
?>
localization.php:
<?php
include('session.php'); //language detector
// determine the value of $lang_file according the one in $lang
$languages = array('en', 'es', 'zh-tw', 'zh-cn');
if (in_array($_SESSION['lang'], $languages)) {
$lang_file = 'lang.'.$_SESSION['lang'].'.php';
} else {
$lang_file = 'lang.zh-tw.php';
}
// translation helper function
function l($localization) {
global $lang;
return $lang[$localization]; }
// include file for final output
include_once 'languages/'.$lang_file;
?>
ModRewrite is your friend. Throw this in your .htaccess file. You may want it to go to your session page instead of index, then redirect with PHP. Note, this only works for one page.
RewriteEngine On
RewriteBase /
# Redirect languages
RewriteRule ^(en|es|zh\-tw|zh\-cn)/?$ index.php?lang=$1 [L]

Categories