Home > front end >  CodeIgniter routes not accepting exceptions different from routing table
CodeIgniter routes not accepting exceptions different from routing table

Time:06-20

somehow I got stuck with my routing rules. I can't set a routing for a page that exceeds the routing rule. For example I have in my routes.php:

$route['(:any)/(:any)/(:any)'] = 'pages/view/$1/$2/$3';
$route['(:any)/(:any)'] = 'pages/view/$1/$2';

so the page loads properly with addresses:

  • mypage.com/value1/value2/value3/
  • mypage.com/value1/value2/

However if a user intentionally enters another value, it will throw a base_url() exception, which is not even handled by my 404 exceptions catch, so I get:

An uncaught Exception was encountered
Type: Error
Message: Call to undefined function base_url()

I can, of course, create another rule to catch 4th value but then, 5th value will throw that error ;)

What I want to achieve is to find a rule, that will match to ANY tree that exceed last rule, something like:

$route['(:any)/(:any)/(:any)/(no matter the value and tree)'] = 'pages/view/$1/$2/$3';
$route['(:any)/(:any)/(:any)'] = 'pages/view/$1/$2/$3';
$route['(:any)/(:any)'] = 'pages/view/$1/$2';

So I won't have any errors even if a user type:

  • mypage.com/value1/value2/value3/4/5/6/7/8/9//10/11/12/13/14/15/blabla/etc...

I'm sure there is a workaround for this (some regex there? (:any) or :any will not work, it will catch only one tree more), however I didn't found any and I'm aware that solution may be simple, but I didn't mastered CI routing yet...

Thank you in advance for any hints.

CodePudding user response:

You can use a normal regex like so :

$route['(:any)/(:any)/(:any)'] = 'pages/view/$1/$2/$3';
$route['(:any)/(:any)'] = 'pages/view/$1/$2';
$route['(:any)/(:any)/(:any)/.*'] = 'pages/view/$1/$2/$3';

The more important question is why doesn't that load a 404? If your custom 404 page is using the base_url() function, autoloading the url helper will fix that error.

  • Related