How to create a multilingual website in codeigniter – beginner tutorial

Spread the love

Multilingual website in codeigniter

Now a days organizations create multilingual websites to serve users in different geographic regions. In this tutorial, you will learn, how to create a multilingual website in codeigniter. In previous tutorial you have learnt how to create a website using  NodeJS and hapi framework.  To read more about codeigniter tutorials, visit our codeigniter tutorials section.

To create a basic multilingual application, you need to do following steps.

1. Download CodeIgniter framework

2. Create a multilingual website in CodeIgniter

3. Configure the application config settings

4. Add English, French, German, Spanish translation language files

5.  Add a language hook

6. Update the controller and view

multilingual website in codeigniter tutorial

Download CodeIgniter framework

To download CodeIgniter framework, visit CodeIgniter home page and download the latest version. The downloaded file is a zip file. Unzip the file and put it in the root directory of your web server. If you have XAMPP installed, rename the folder to multilingual app in codeigniter and put it in the htdocs or www folder.

CodeIgniter application’s skeleton is already provided. It contains application, system folder and other files. Application directory contains controllers, core, views, libraries, hooks, language and other important directories.

multilingual app in codeigniter - directory structure

Create a multilingual website in CodeIngniter

Open the project directory in your favorite editor such as visual studio code, atom or phpstorm.

Configuration of the project

Before development of the application, we need to configure the project.

Change base URL for the application

Open config.php in application/config.php. Go to the line, base_url and change it to.

$config['base_url'] = 'http://localhost/ci_multilingual_app/';

Remove index.php from the URL

In a codeigniter application, the URL for the controller and actions contains index.php.

http://localhost/index.php/controller

To create a SEO friendly URL we need to remove index.php. Do the steps given.

Create a .htaccess file

Open root directory of the project and create a .htaccess file. Add the code into the file.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Remove index.php file from index_page in config

Open config.php file from the folder “application/config”. Go to the line.

$config['index_page'] = "index.php"

Remove index.php in from the $config[‘index_page’].

$config['index_page'] = ""

Change uri_protocol in config file

Open config file in “application/config” directory.  Change the line

$config['uri_protocol'] = "AUTO"

with

$config['uri_protocol'] = "REQUEST_URI"

Autoload URL helper

Open autoload.php in config folder and go to

$autoload['helper']

and change it as

$autoload['helper'] = array('url');

Autoload libraries

Open autoload.php in config folder and go to the line add session library.

$autoload['libraries'] = array('session');

Create language translation files

Open application/language directory. Let us create language files with a welcome message and content key.

Create an English translation file

Create a folder named English in application/language folder. Create a file named content_lang.php with the code.

<?php

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

$lang['welcome'] = 'Welcome to our website';
$lang['message'] = 'Our mission is to provide professional and highly creative web design
                    services and other related services to a wide range of potential customers all over the globe.';

Create a Spanish translation file

Create a folder named Spanish in application/language folder. Create a file named content_lang.php in it.

<?php

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

$lang['welcome'] = 'Bienvenido a nuestro sitio web';
$lang['message'] = 'Nuestra misión es proporcionar servicios de diseño web profesionales y altamente creativos y otros 
                    servicios relacionados a una amplia gama de clientes potenciales en todo el mundo.';

Create a German translation file

Create a folder named German in application/language folder. Create a file named content_lang.php in it.

<?php

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

$lang['welcome'] = 'Willkommen auf unserer Webseite';
$lang['message'] = 'Unsere Mission ist es, einem breiten Spektrum potenzieller Kunden auf der ganzen 
                    Welt professionelle und äußerst kreative Webdesign-Services und damit verbundene Dienstleistungen anzubieten.';

Create a French translation file

Create a folder named French in application/language folder. Create a file named content_lang.php in it.

<?php

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

$lang['welcome'] = 'Bienvenue sur notre site';
$lang['message'] = 'Notre mission est de fournir des services de conception Web professionnels et très créatifs, 
                   ainsi que d’autres services connexes, à un large éventail de clients potentiels dans le monde entier.';

Create a Language Hook for the multilingual website in codeigniter

To create a new language hook, change the configuration.

Enable hook in config.php

Open config.php file in config directory. Set value for enable_hooks to TRUE.

$config['enable_hooks'] = TRUE

Define language hook configuration

Open hooks.php file in config directory. Define the new hook.

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

Create a LangaugeLoader class for multilingual website in codeigniter

Create LangaugeLoader.php file in application/hooks directory. A LanguageLoader class is created. Initialize function loads the content based on selected language by user.

 <?php

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

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

Add code to controller

Open Welcome.php file in controllers directory. Remove the existing code and add the code.

<?php

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

class Welcome extends CI_Controller {

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

  public function index()
  {
    $this->session->set_userdata('site_lang',  "english");
    $this->load->view('welcome_message');
  }

  public function switchLang($language = "") {
    $this->session->set_userdata('site_lang', $language);
    header('Location: http://localhost/ci_multilingual_app/');
  }
}

The index action, session’s set_userdata method sets site_lang to default value to English and loads the view template welcome_message.

Switch Language function in welcome controller

An function named switchLang is added. This action accepts $language parameter and is set to the session as $language. User is redirected to the home page.

Update View file

Open welcome_message.php file in views directory. Replace the code below into the body of the page.

<div id="container">
<div style ='margin:0 auto; text-align:center'>
      <a href="<?php echo base_url("welcome/switchLang/english"); ?>">English</a> |
      <a href="<?php echo base_url("welcome/switchLang/french"); ?>">French</a> |
      <a href="<?php echo base_url("welcome/switchLang/german"); ?>">German</a> |
      <a href="<?php echo base_url("welcome/switchLang/spanish"); ?>">Spanish</a>
    </div>
  <h1><?php echo $this->lang->line('welcome') ?></h1>
  
  <div id="body">
    
    <p><?php echo $this->lang->line('message') ?></p>
    </div>
</div>

Running the application

Open your favorite browser and add following URL in the address.

http://localhost/ci_multilingual_app/

multilingual website in codeigniter - english page

View French translation

Click on French link.

multilingual website in codeigniter - french page

View German translation

Click on German link

multilingual website in codeigniter - german page

View Spanish translation

Click on Spanish link

multilingual website in codeigniter - spanish page

Summary

In this tutorial you have learnt how to create a multilingual site in codeigniter. We created a codeigniter application. Added a language hook was added. You can download the source code of this the tutorial from GitHub

multilingual website in codeigniter - github source code

Follow us on Twitter , like our Facebook page to stay updated about out upcoming tutorials.

Previous Article

 

Next Article

 

Related Article

 

Check Also

generate a pdf using php

How to Generate a PDF using php

Spread the loveLast updated:28th March, 2021How to Generate a PDF using php In the modern …