[eluser]Henrik Pejer[/eluser]
Hello fellow CI code crunchers!
I decided to start my venture down the CI-path with a little fix for, as I'd call it, complete custom 404 controller page.
I searched the forum for how I should make a custom 404-page. It seemed like I should extend the Exceptions-class. The only problem is that the 404-event triggers before all the base classes are loaded: I have no controller, database etc.
I think the reason for this is based on security: not letting an ill typed URL somehow get run by CI as a normal controller.
But I realized that by extending not the Exceptions class but rather the Router-class, I was able to 'fool' CI to use one of my own controller, and let the system load as normal.
All I did was copy the '_validate_segments'-function and slightly modify it to return the custom controller I wanted to use as 404-page. My custom 404-controller is called 'custom404controller' and located in my application/controllers/-folder, like any other controller.
A word of advice: before you use this, test it thoroughly! Also make sure that by using this way of handling 404-errors, you do not compromise the security of you application.
Also,this is for version 1.5.3 of CI.
This is the extension that seemed to do the trick:
Code:
class MY_Router extends CI_Router{
function MY_Router(){
parent::CI_Router();
}
function _validate_segments($segments)
{
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
# HENRIK PEJER MOD: commented out the line below, added the line below that
#show_404();
return $this->custom_404();
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Can't find the requested controller...
# HENRIK PEJER MOD: commented out the line below, added the line below that
#show_404();
return $this->custom_404();
}
function custom_404(){
# return an array with the name of the controller we want as the 404-handler...
return array('custom404controller');
}
}
Any advice, tips or concerns regarding the code above would be very interesting to hear.
Take care and happy CI:ing!