URI Segments in CodeIgniter Framework


In CodeIgniter Project, Open autoload.php file in config folder. Add url helper to helper config as below:

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

In CodeIgniter Project, Open config.php file in config folder. Set value for base_url config as below:

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

In CodeIgniter Project, Open config.php file in config folder. Set value for uri_protocol config as below:

$config['uri_protocol']	= 'PATH_INFO';




Create new PHP file named demo.php in controllers folder as below:

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

class Demo extends CI_Controller
{

    public function index()
    {
        $this->load->view('demo/index');
    }

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

In CodeIgniter Project, Open routes.php file in config folder. Set value for default_controller as below:

$route['default_controller'] = 'demo';




Create new folder named demo in views folder. In this folder, create new views as below:

Create new PHP file named index.php as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
	<head>
		<title>Demo 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:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<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>




Access index action in Demo controller with following url: http://localhost:9092/LearnCodeIgniterWithRealApps/demo/index

Output

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

Output

I recommend you refer to the books below to learn more about the knowledge in this article: