Musings of a startup founder

Musings of a startup founder


Chris Duell, co-founder @ elev.io

Chris Duell
Author

CEO & Co-founder of elev.io

Share


elevio

Twitter


Better 404 catching with CodeIgniter

CodeIgniter has a built in 404 catch, however it displays a pretty plain page of just some text in a box. It would be much nice if you were able to display your…

Chris DuellChris Duell

CodeIgniter has a built in 404 catch, however it displays a pretty plain page of just some text in a box. It would be much nice if you were able to display your own custom 404 page that was in your sites styling.

There is an option to edit the routes file and updated the $route[‘404_override’] variable to point to a custom 404 page of your own, however this is only ever called if it the controller isn’t found. If the controller is found, but a method in it isn’t, the plain looking default 404 is used. Here’s a quick workaround.

If you haven’t already, create a MY_Controller.php file in your application/core folder with the following:

Add into that file a _remap() function as below

function _remap($method) { if (in_array(strtolower($method), array_map('strtolower', get_class_methods($this)))) { $uri = $this->uri->segment_array(); unset($uri[1]); unset($uri[2]); call_user_func_array(array($this, $method), $uri); } else { redirect('404'); } }

The _remap function is called for every page load instead of the normal method as an override. What we are doing here is checking that the method we are looking for actually exists, if it does, run it. If however it can’t be found, then the user is redirected to a 404 page.

You’ll also need to add a new entry to your routes.php file the directs ‘404’ to the page of your choice. i.e.,

$route['404'] = 'errors/show404';

Perhaps there’s a better way to do this, if not, it would be nice if the core catered for this situation better.

Chris Duell
Author

Chris Duell

CEO & Co-founder of elev.io

Comments