Codeigniter在会话中保存选定的语言

时间:2016-07-11 12:04:07

标签: php codeigniter

我有codeigniter应用程序,默认语言是英语,我有拖动语言切换到英语。
问题是,当我将语言从english切换到eg:arabic时,相同的页面正在发生变化,但当我转到另一个页面时,它又重新回到了英语。

MY_Lang.php

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class MY_Lang extends CI_Lang {

// Add your languages here
private $languages = array(
'en' => 'english',
'ar' => 'arabic'
);

// special URIs (not localized)
    private $special = array (
'admin',
'assets',
'editor'
);

// where to redirect if no language in URI
private $uri;
private $default_uri;
private $lang_code;

/**************************************************/

function MY_Lang()
{
    parent::__construct();

    global $CFG;
    global $URI;
    global $RTR;

    $this->uri = $URI->uri_string();
    $this->default_uri = $RTR->default_controller;

    $uri_segment = $this->get_uri_lang($this->uri);
    $this->lang_code = $uri_segment['lang'] ;

    $url_ok = false;
    if ((!empty($this->lang_code)) && (array_key_exists($this->lang_code, $this->languages)))
    {
        $language = $this->languages[$this->lang_code];
        $CFG->set_item('language', $language);
        $url_ok = true;
    }

    if ((!$url_ok) && (!$this->is_special($uri_segment['parts'][0]))) // special URI -> no redirect
    {
        // set default language
        $CFG->set_item('language', $this->languages[$this->default_lang()]);

        $uri = (!empty($this->uri)) ? $this->uri: $this->default_uri;
        $uri = ($uri[0] != '/') ? '/'.$uri : $uri;
        $new_url = $CFG->config['base_url'].$this->default_lang().$uri;

        header("Location: " . $new_url, TRUE, 302);
        exit;
    }
}

和view.php

<div class="lang-bar pull-left">
<a href="<?php echo site_url($this->lang->switch_uri('ar'));?>" class="btn btn-success">Ar</a>
<a href="<?php echo site_url($this->lang->switch_uri('en'));?>" class="btn btn-success">En</a>
</div>

所以如何保持语言直到关闭页面

2 个答案:

答案 0 :(得分:1)

I don't know exactly how the library works, but maybe you don't load session library to keep language values accross pages. Here's another lib I like to use: https://github.com/devtime-share/codeigniter-kitlang

答案 1 :(得分:0)

最好的选择是将所选语言保存在数据库中,然后在以后检索它而不是使用会话。与您尝试找出如何更改语言的情况相同,但是我使用的是数据库而不是会话。