Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 829
andershagbard Avatar asked Jul 19 '14 20:07

andershagbard


2 Answers

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.

like image 147
Adeel Raza Avatar answered Nov 16 '22 09:11

Adeel Raza


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
like image 3
andershagbard Avatar answered Nov 16 '22 08:11

andershagbard