How to route the URI with parameters to a method in codeigniter?

On codeigniter 3

Make sure your controller has first letter upper case on file name and class name

application > controllers > Products_controller.php

<?php

class Products_controller extends CI_Controller {

    public function index() {

    }

    public function display() {

    }
}

On Routes

$route['products/display'] = 'products_controller/display';
$route['products/display/(:any)'] = 'products_controller/display/$1';
$route['products/display/(:any)/(:any)'] = 'products_controller/display/$1/$2';
$route['products/display/(:any)/(:any)/(:any)'] = 'products_controller/display/$1/$2/3';

Docs For Codeigniter 3 and 2

http://www.codeigniter.com/docs


Maintain your routing rules like this

$route['products/display/(:any)/(:any)/(:any)'] = 'Products_controller/display/$2/$3/$4';

Please check this link Codeigniter URI Routing


In CI 3.x the (:any) parameter matches only a single URI segment. So for example:

$route['method/(:any)/(:any)'] = 'controller/method/$1/$2';

will match exactly two segments and pass them appropriately. If you want to match 1 or 2 you can do this (in order):

$route['method/(:any)/(:any)'] = 'controller/method/$1/$2';
$route['method/(:any)'] = 'controller/method/$1';

You can pass multiple segments with the (.+) parameter like this:

$route['method/(.+)'] = 'controller/method/$1';

In that case the $1 will contain everything past method/. In general I think its discouraged to use this since you should know what is being passed and handle it appropriately but there are times (.+) comes in handy. For example if you don't know how many parameters are being passed this will allow you to capture all of them. Also remember, you can set default parameters in your methods like this:

public function method($param=''){}

So that if nothing is passed, you still have a valid value.

You can also pass to your index method like this:

$route['method/(:any)/(:any)'] = 'controller/method/index/$1/$2';
$route['method/(:any)'] = 'controller/method/index/$1';

Obviously these are just examples. You can also include folders and more complex routing but that should get you started.


In CodeIgniter 4

Consider Product Controller with Show Method with id as Parameter

http://www.example.com

/product/1

ROUTE Definition Should be

$routes->get("product/(:any)", "Com\Atoconn\Product::show/$1");