URI Segments in CodeIgniter 4

Download the latest version of CodeIgniter 4 and unzip source code to new folder named LearnCodeIgniter4WithRealApps

Cut index.php and htaccess files in public folder to root folder of project

Open index.php in root folder find to line 16 replace path to Paths.php file as below:

$pathsPath = realpath(FCPATH . '/app/Config/Paths.php');

Open App.php in app/Config folder find to line 36 remove index.php string in $indexPage variable as below:

public $indexPage = '';




Open App.php file in app/Config folder. Set value for $baseURL variable as below:

public $baseURL = 'http://localhost:8095/LearnCodeIgniter4WithRealApps/';

Create new PHP file named Demo.php in app/Controllers folder as below:

<?php

namespace App\Controllers;

class Demo extends BaseController
{
	public function index()
	{
		return view('demo/index');
	}

	public function display()
	{
		$data['controller_name'] = $this->request->uri->getSegment(1);
		$data['action_name'] = $this->request->uri->getSegment(2);
		$data['parameter_1'] = $this->request->uri->getSegment(3);
		$data['parameter_2'] = $this->request->uri->getSegment(4);
		$data['segments'] = $this->request->uri->getSegments();
		return view('demo/result', $data);
	}
}

Create new folder named demo in app/Views folder. In this folder, create new PHP file named index.php as below:

<html>

<head>
    <title>Index Page</title>
</head>

<body>

    <a href="<?php echo site_url('demo/display/123/abc'); ?>">Display Values Segments</a>

</body>

</html>




Create new PHP file named result.php as below:

<html>
	<head>
		<title>Result Page</title>
	</head>
	<body>

		<h3>Values Segments</h3>
		Controller Name: <?php echo $controller_name; ?>
		<br>
		Action Name: <?php echo $action_name; ?>
		<br>
		Parameter 1: <?php echo $parameter_1; ?>
		<br>
		Parameter 2: <?php echo $parameter_2; ?>

		<h3>Segment Array</h3>
		<?php foreach($segments as $segment) { ?>
			<?php echo $segment; ?>
			<br>
		<?php } ?>

	</body>
</html>

Open Routes.php file in app/Config folder. Set default controller as below:

$routes->get('/', 'Demo::index');




Access index action in Demo controller with following url: http://localhost:8095/LearnCodeIgniter4WithRealApps/demo/index

Output




Click Display Values Segments link will call to display action in Demo controller with following url: http://localhost:8095/LearnCodeIgniter4WithRealApps/index.php/demo/display/123/abc

Output