bafromca
bafromca

Reputation: 1946

Catch-all Controller/Route

If I want to catch every single non existing URL that was passed to my web application and serve them a view without serving a 404, how would I do that?

Essentially I need to record the statistics based on these hits, but I need to do it by serving content and not a 404 error.

As far as I can tell from application/config/routes.php, I could use

$route['default_controller'] = 'catchall';

but I need that for my actual web application.

I could also use

$route['404_override'] = 'catchall';

but I don't want to throw 404s.

I tried using

$route['(:any)'] = '$1';

but I need to record the entire URL (e.g. any length of segments), not just the first segment.

Upvotes: 7

Views: 3521

Answers (3)

birderic
birderic

Reputation: 3765

Use $route['(:any)'] = 'catchall_controller'. Then in your controller you can access the URI segments using $this->uri->segment(n).

Upvotes: 7

Chris Schmitz
Chris Schmitz

Reputation: 8257

Have you tried adding multiple catch all routes for different amounts of segments?

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

I'm guessing that would work, but there might be a more elegant way to do it.

Upvotes: 1

Robert Noack
Robert Noack

Reputation: 1316

I don't know the difference between codeigniter and normal PHP, but, in normal php, you can edit the htaccess or whatever to define a custom 404 page.

In the custom 404 page, do something like the equivalent of this: $requested=$_SERVER['REQUEST_URI'];

to get the URL which was requested.... do your handling... and do this to clear the 404:

header("HTTP/1.1 200 OK"); header("Status: 200 OK");

Then, include your html or whatever you want to serve.

Upvotes: 0

Related Questions