Skip to content
Advertisement

How to deal with extra “/” in phpleague route?

I am setting endpoints for my web application like this:

$router = new LeagueRouteRouteCollection;

function user_action (Request $request, Response $response) {
    // some logic
    .
    .
    .
    return $response;
}

$router->addRoute('GET', '/user', 'user_action');

/user endpoint works well.

However when I use /user/ (extra slash in the end) I get a

LeagueRouteHttpExceptionNotFoundException

I want both endpoints to point to same function. I can achieve the desired behavior by adding routes for both endpoints separately:

$router->addRoute('GET', '/user', 'user_action');
$router->addRoute('GET', '/user/', 'user_action');

What is the recommended way to resolve this?

Advertisement

Answer

There are two options

  1. You can use htaccess to strip the trailing slash from the url.
  2. Send the dispatcher the url without the trailing slash.

Solution 1: htaccess

Add the following rewrite rule to your .htacces:

RewriteRule ^(.*)/$ /$1 [L,R=301]

Solution 2: dispatcher

After you’ve created the router from a RouteCollection, you get the dispatcher and dispatch the routes:

$router = new RouteCollection();
$dispatcher = $router->getDispatcher();
$response = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo());

The url which is send to the dispatcher can easily be adjusted:

$url = $request->getPathInfo();

// if url ends with a slash, remove it
$url = rtrim($url, '/');

$response = $dispatcher->dispatch($request->getMethod(), $url);

Two easy solutions, which one you use depends on you.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement