php-mvc icon indicating copy to clipboard operation
php-mvc copied to clipboard

Slash at the end of url

Open pagodzik opened this issue 5 years ago • 4 comments

Hi

Is it possible that two urls: mysite.com/admin mysite.com/admin/ show the same? I did $router->add('admin/', ['controller' => 'Home', 'action' => 'index', 'namespace' => 'Admin']); $router->add('admin', ['controller' => 'Home', 'action' => 'index', 'namespace' => 'Admin']); but maybe there is simplier method?

pagodzik avatar Nov 25 '20 13:11 pagodzik

Currently that is the way you'd have to do it - you could modify the router though if you like, adding something like the following inside the loop where the routes are matched in the match method:

$route = trim($route, '/');

(I'm working on an update to the framework that is more robust to things like this, so it includes this code to make routes work with and without slashes)

daveh avatar Nov 26 '20 05:11 daveh

I did change which works for me - I think that we have trim rather url than route.

public function match($url)
{
    foreach ($this->routes as $route => $params) {
        $url = trim($url, '/').'/';
        if (preg_match($route, $url, $matches)) {
      ...

And in index.php all route should '/' at the end.

pagodzik avatar Nov 26 '20 09:11 pagodzik

the last solution of @pagodzik Works for me too

diogenesjup avatar Aug 18 '21 17:08 diogenesjup

You can modify the regex in the add function in Core/Router.php to achieve this.

In this line: $route = '/^' . $route . '$/i';

Add \/? before the $ to make the slash optional, like this: $route = '/^' . $route . '\/?$/i';

Now you can add your route in the index.php without the ending slash, and it will resolve to both URL cases.

dedelkov avatar Feb 18 '24 13:02 dedelkov