URI segment in Codeigniter4

We can fetch parts of the url in Codeigniter4 using the getSegments() function. This is similar to CI3 call $this->uri->segment function but with a slight difference. Let us look at an example where we have to load different pages based on language. We will first create routing rules at app/Config/Routes.php file.
Add line $routes->get(‘/(:segment)’, ‘Home::getLanguagePage’);

For your app/Controllers/Home.php below is the code.

<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    {
        return $this->getLanguagePage();
    }

    public function getLanguagePage(){
        $segments = $this->request->uri->getSegments(); //returns array
        $type = (isset($segments[0])) ? $segments[0] : "en";
        if($type == "es"){
            return view('language_home/spanish_home');
        }else if($type == "fr"){
            return view('language_home/french_home');
        }else if($type == "zh"){
            return view('language_home/chinese_home');
        }else{
            return view('language_home/english_home'); //default
        }
    }
}

Let us create the view pages mentioned in the controller file. Go to app/Views and create a folder “language_home” .
Add 4 files inside language home with different contents as below.

spanish_home.php  

Bienvenida 
english_home.php

Welcome!
french_home.php

Bonjour et bienvenue
chinese_home.php

你好,欢迎光临

Now when you run the code on your local machine; say with url “http://localhost:8080/fr” the page with french is displayed. Similarly if you open url “http://localhost:8080/zh” the Chinese home page is displayed on browser. We are able to read the uri segment and route to pages accordingly using the line

$segments = $this->request->uri->getSegments();

$segments is an array of the url segments.

Leave a Reply