CodeIgniter Forums

Full Version: [Snippet] Switch language with URL
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Some people around net are digging about how to make their website using multiple languages and allow users to switch this from within URL without modifying routes, adding new routes or using some prefixes/parameters in your controllers.

Some examples on what we are trying to get: - content with default language - content with english language - content with german language - content with russian language

The simple trick is in modifying query url and checking if first element is withing langeages list. Then just to remove this one, to get modified url parameter.

First, you will need to alter your "config.php" file and add a list of all available languages.
$config['language']    = 'english';
$config['languages']    = [
  'english' => 'en',
  'german' => 'de',
  'russian' => 'ru'

Now we will have to create new file "MY_Router.php" in "/application/core" folder, with following content:
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Router extends CI_Router {

    protected function _parse_routes()
    // Language detection over URL
    if($this->uri->segments[1] == $this->config->config['language']) {
    if(array_search($this->uri->segments[1], $this->config->config['languages'])) {
      $this->config->config['language'] = array_search($this->uri->segments[1], $this->config->config['languages']);
    // Return default function
    return parent::_parse_routes();

Thats it. Now for example default "welcome" route will be accessible thru "/", "/en", "/de", "/ru" url, you will just have to add some text Smile

There is also some other magic, how you can use your Database to get all text translated Smile

It's a good solution! Thank you for that!
Use the codeigniter language library with this class extension: URI Language Identifier. I also use this controller for switching the language

class LangSwitch extends CI_Controller {

public function __construct() {
public function switchLanguage($language = "") {

$referrer = $this->agent->referrer();

$l = substr($referrer, strlen(base_url()));

if (empty($match)) {
redirect(base_url().$language ,'refresh');
$redirect_url = base_url().$language.$match[1];
site_url() and base_url() function
not work....
For site_url() and base_url() you need to load the url_helper