Teguh Arief

Multi-Language Setup in CodeIgniter

Multi-language setup in CodeIgniter demonstrating various language options and their implementation.

Teguh Arief

Published on: September 24, 2020

Share:

The multi-language setup feature, also known as internationalization, is essential for any modern web application aiming for a global audience. In this tutorial, we'll walk you through how to enable multi-language setup in CodeIgniter. This solution primarily covers non-editable text within your application but doesn't delve into multi-language content retrieved from a database.

1. Configure Default Language

Open the `application/config/config.php` file and specify your site's default language:

$config['language'] = 'english';

2. Create Multi-Language Files

Create separate language files and place them within the `application/language/` directory, each in its own sub-directory (e.g., `english`, `indonesian`, `chinese`, `arabic`). Your language file structure should look like this:

  • application/language/english/welcome_lang.php
  • ...
  • application/language/indonesian/welcome_lang.php
  • ...
  • application/language/chinese/welcome_lang.php
  • ...
  • application/language/arabic/welcome_lang.php
  • ...
  • ...

Sample language files would appear as follows:

`english/welcome_lang.php`

<?php
$lang['welcome_message'] = 'Welcome to our website!';
$lang['about_us'] = 'About Us';
?>

`indonesian/welcome_lang.php`

<?php
$lang['welcome_message'] = 'Selamat datang di website kami!';
$lang['about_us'] = 'Tentang Kami';
?>

`chinese/welcome_lang.php`

<?php
$lang['welcome_message'] = '欢迎来到我们的网站!';
$lang['about_us'] = '关于我们';
?>

`arabic/welcome_lang.php`

<?php
$lang['welcome_message'] = 'مرحبا بكم في موقعنا!';
$lang['about_us'] = 'معلومات عنا';
?>

3. Load Language Files

Open `application/controllers/welcome.php` and add the following code within the controller’s `__construct()` function to enable the multi-language setup in CodeIgniter:

public function __construct() {
    parent::__construct();
    $this->load->helper('language');
    $this->lang->load('welcome');
}

Next, open `application/config/hooks.php` and define a hook to dynamically load languages:

$hook['post_controller_constructor'] = array(
    'class'    => 'LanguageLoader',
    'function' => 'initialize',
    'filename' => 'LanguageLoader.php',
    'filepath' => 'hooks'
);

Create the `LanguageLoader` class in `LanguageLoader.php` inside the `application/hooks/` directory:

<?php
class LanguageLoader {
    function initialize() {
        $ci =& get_instance();
        $ci->load->helper('language');
        $site_lang = $ci->session->userdata('site_lang');
        if ($site_lang) {
            $ci->lang->load('message', $ci->session->userdata('site_lang'));
        } else {
            $ci->lang->load('message', 'english');
        }
    }
}
?>

4. Switch Between Different Languages

To facilitate a multi-language setup in CodeIgniter, create a `Langswitch` class in `langswitch.php` within the `application/controllers/` directory:

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

class Langswitch extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    public function switchLanguage($language = "") {
        $language =  ($language != "") ? $language : "english";
        $this->session->set_userdata('site_lang', $language);
        redirect(base_url());
    }
}
?>

5. Core System Setup for Pages

For your pages to work seamlessly with the multi-language setup in CodeIgniter, you'll need to configure the core system. Create an `MY_Config` class in `MY_Config.php` inside the `application/core/` directory:

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

class MY_Config extends CI_Config {

    function site_url($uri = '') {
        if (is_array($uri)) {
            $uri = implode('/', $uri);
        }

        if ($uri == '') {
            return parent::site_url($uri);
        }

        $CI =& get_instance();
        if (!$CI->lang->has_language($uri)) {
            $uri = $CI->lang->localized($uri);
        }

        return parent::site_url($uri);
    }
}
?>

Then, to correctly load the language for your multi-language setup in CodeIgniter, create an `MY_Lang` class in `MY_Lang.php` inside the `application/core/` directory:

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

class MY_Lang extends CI_Lang {

    var $languages = array(
        'en' => 'english',
        'id' => 'indonesian',
        'cn' => 'chinese',
        'sa' => 'arabic'
    );

    var $special = array(""); // Add any special URIs that don't need language prefix
    var $default_uri = '';

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

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

        $segment = $URI->segment(1);

        if (isset($this->languages[$segment])) { // URI with language -> ok
            $language = $this->languages[$segment];
            $CFG->set_item('language', $language);
        } else if ($this->is_special($segment)) { // special URI -> no redirect
            return;
        } else {
            $CFG->set_item('language', $this->languages[$this->default_lang()]);
            header("Location: " . $CFG->site_url($this->localized($this->default_uri)), TRUE, 302);
            exit;
        }
    }

    function lang() {
        global $CFG;
        $language = $CFG->item('language');

        $lang = array_search($language, $this->languages);
        if ($lang) {
            return $lang;
        }

        return NULL; // this should not happen
    }

    function is_special($uri) {
        $exploded = explode('/', $uri);
        if (in_array($exploded[0], $this->special)) {
            return TRUE;
        }
        if (isset($this->languages[$uri])) {
            return TRUE;
        }
        return FALSE;
    }

    function switch_uri($lang) {
        $CI =& get_instance();

        $uri = $CI->uri->uri_string();
        if ($uri != "") {
            $exploded = explode('/', $uri);
            if ($exploded[0] == $this->lang()) {
                $exploded[0] = $lang;
            }
            $uri = implode('/', $exploded);
        }
        return $uri;
    }

    function has_language($uri) {
        $first_segment = NULL;

        $exploded = explode('/', $uri);
        if (isset($exploded[0])) {
            if ($exploded[0] != '') {
                $first_segment = $exploded[0];
            } else if (isset($exploded[1]) && $exploded[1] != '') {
                $first_segment = $exploded[1];
            }
        }

        if ($first_segment != NULL) {
            return isset($this->languages[$first_segment]);
        }

        return FALSE;
    }

    function default_lang() {
        foreach ($this->languages as $lang => $language) {
            return $lang;
        }
    }

    function localized($uri) {
        if ($this->has_language($uri)
            || $this->is_special($uri)
            || preg_match('/(.+)\.[a-zA-Z0-9]{2,4}$/', $uri)) {
            // Do nothing
        } else {
            $uri = $this->lang() . '/' . $uri;
        }

        return $uri;
    }
}
?>

6. Set Default Route Controller

To ensure your multi-language setup in CodeIgniter routes correctly, configure your `application/config/routes.php` file:

$route['^en$'] = $route['default_controller'];
$route['^id$'] = $route['default_controller'];
$route['^cn$'] = $route['default_controller'];
$route['^sa$'] = $route['default_controller'];

7. Define Links to Switch Multi-Language

Finally, to allow users to switch languages in your multi-language setup in CodeIgniter, you'll need to define links in your views, pointing to the `Langswitch` controller:

<a href="<?php echo site_url('langswitch/switchLanguage/english'); ?>">English</a>
<a href="<?php echo site_url('langswitch/switchLanguage/indonesian'); ?>">Indonesian</a>
<a href="<?php echo site_url('langswitch/switchLanguage/chinese'); ?>">Chinese</a>
<a href="<?php echo site_url('langswitch/switchLanguage/arabic'); ?>">Arabic</a>

8. Fetching Line of Text

To display localized text within your views (e.g., in `application/views/welcome.php`), use the `lang()` function:

<h1><?php echo $this->lang->line('welcome_message'); ?></h1>
<p><?php echo $this->lang->line('about_us'); ?></p>

Related Posts

Building a NestJS CRUD application with MongoDB and Mongoose for a superior backend.

NestJS CRUD with MongoDB using Mongoose

Learn to build a robust backend with NestJS, covering CRUD operations using MongoDB and Mongoose, from setup to creating, reading, and updating.

Read More
CI/CD pipeline for React.js deployment using Visual Studio Code, GitHub Actions, and cPanel FTP.

Streamline React.js Deployment: CI/CD with VS Code Integration

Learn to set up robust CI/CD for React.js with VS Code, GitHub Actions, and FTP on cPanel. This guide covers everything.

Read More
Illustrated guide for creation search engine on Laravel sites using Solr.

Creation Search Engine on Laravel Sites Using Solr

Build powerful search on Laravel sites using Solr! This guide covers Solr configuration, Solarium integration, and best practices for efficient search.

Read More