php - How to deal with extra "/" in phpleague route? -


i setting endpoints web application this:

$router = new league\route\routecollection;  function user_action (request $request, response $response) {     // logic     .     .     .     return $response; }  $router->addroute('get', '/user', 'user_action'); 

/user endpoint works well.

however when use /user/ (extra slash in end)

league\route\http\exception\notfoundexception

i want both endpoints point same function. can achieve desired behavior adding routes both endpoints separately:

$router->addroute('get', '/user', 'user_action'); $router->addroute('get', '/user/', 'user_action'); 

what recommended way resolve this?

there 2 options

  1. you can use htaccess strip trailing slash url.
  2. send dispatcher url without trailing slash.

solution 1: htaccess

add following rewrite rule .htacces:

rewriterule ^(.*)/$ /$1 [l,r=301] 

solution 2: dispatcher

after you've created router routecollection, dispatcher , dispatch routes:

$router = new routecollection(); $dispatcher = $router->getdispatcher(); $response = $dispatcher->dispatch($request->getmethod(), $request->getpathinfo()); 

the url send dispatcher can adjusted:

$url = $request->getpathinfo();  // if url ends slash, remove if (substr($url, -1) === '/') {     $url = substr($url, 0, strlen($url) - 1); }  $response = $dispatcher->dispatch($request->getmethod(), $url); 

two easy solutions, 1 use depends on you.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -