Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow optional trailing slash when using optional parameter

Tags:

php

slim

Given this path: /page(/:pageID), how can I allow the following variations:

  • /page and /page/ (even if the pageID part is missing.
  • /page/1 and /page/1/

Thank you.

like image 370
Francisc Avatar asked Jun 28 '12 20:06

Francisc


3 Answers

You must define your route this way:

$app->get('/page(/:id/?)', function ($id = NULL) use ($app) {
    ; // your code
});
like image 55
nilfalse Avatar answered Nov 25 '22 01:11

nilfalse


The answer provided by @inst would not work here (Slim 2.0.0 running on XAMPP): /page/ gives out a 404.

This works in all four cases though:

$app->get('/page(/)(:id/?)', function ($id = NULL) use ($app) {
  echo 'success';
});
like image 22
Fabien Snauwaert Avatar answered Nov 25 '22 02:11

Fabien Snauwaert


As stated in the documentation, optional segments may be unstable depending on the usage. For example, with the answer given by Fabien Snauwaert, and the following routes:

/:controller(/)(:action(/)(:overflow+/?))
/:controller(/)(:action(/:overflow+/?))

If not filled all the arguments, when obtain param values, these will be in a position to the right, resulting in action == controller and overflow == action.

To prevent this, a simple solution is to put the optional slash at the end of the route.

/:controller(/:action(/:overflow+))/?
/:controller(/:action(/:overflow+))(/)

And it is more readable, isn't it?

I can not comment on others answers, so I write here a detail concerning the Igor response.

One "problem" with this approach is that if the user tries to access a page that does not exist, and also do with a trailing slash, will be a 301 redirect to display a 404 page. Maybe a little weird.

like image 20
seus Avatar answered Nov 25 '22 01:11

seus