andershagbard
andershagbard

Reputation: 1137

Codeigniter - Get current route

I'm looking for help to know which route my Codeigniter application goes through.

In my application folder in config/routes.php i got some database generated routes, could look like this:

$route["user/:any"] = "user/profile/$1";
$route["administration/:any"] = "admin/module/$1";


If i for example to go domain.net/user/MYUSERNAME, then i want to know that i get through the route "user/:any".
Is it possible to know which route it follows?

Upvotes: 6

Views: 19298

Answers (4)

Aldo
Aldo

Reputation: 923

For CodeIgniter 4:

var_dump(service('router')->getMatchedRoute());

It will return something like this:

[
    "{locale}/(.*)",
    "\App\Controllers\Home_controller::any/home"
];

Upvotes: 2

andershagbard
andershagbard

Reputation: 1137

I used @Ochi's answer to come up with this.

$routes = array_reverse($this->router->routes); // All routes as specified in config/routes.php, reserved because Codeigniter matched route from last element in array to first.
foreach ($routes as $key => $val) {
$route = $key; // Current route being checked.

    // Convert wildcards to RegEx
    $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key);

    // Does the RegEx match?
    if (preg_match('#^'.$key.'$#', $this->uri->uri_string(), $matches)) break;
}

if ( ! $route) $route = $routes['default_route']; // If the route is blank, it can only be mathcing the default route.

echo $route; // We found our route

Upvotes: 3

Ochi
Ochi

Reputation: 1478

looking at the latest version it's not possible without using custom router as ROUTEKEY is used and overwritten trying to parse the route

if you would like to create and use custom class it's only a matter of saving original $key to another variable and setting it as a class property for later use when you have a match (line 414 before "return" - you can get that key later as e.g. $this->fetch_current_route_key()) - other thing to remember is that this kind of code modification is easy to break if original class will change (update) so keep that in mind

Upvotes: 1

Adeel Raza
Adeel Raza

Reputation: 634

One way to know the route could be using this:

$this->uri->segment(1);

This would give you 'user' for this url:

domain.net/user/MYUSERNAME

By this way you can easily identify the route through which you have been through.

Upvotes: 8

Related Questions