How can I redirect a 404 Error in a custom 404 page using Codeigniter?


Question

Kind sirs, I'm using Codeigniter to build a blog. I might need a way to redirect a 404 error into a custom 404 page. Just like what Abduzeedo.com's 404 page. Is it possible to control this by using routes? Or should i use controllers to direct it to another view? Thanks very much!

1
23
2/22/2010 9:59:06 AM

Accepted Answer

there is another way which I use: by overriding Exception core class of Codeigniter. Firstly make sure your config file(system/application/config/config.php) subclass prefix is as following $config['subclass_prefix'] = 'MY_';

Then make a file named MY_Exceptions.php in system/application/libraries. Then override the function show_404() function here as follows.

class MY_Exceptions extends CI_Exceptions{
    function MY_Exceptions(){
        parent::CI_Exceptions();
    }

    function show_404($page=''){    

        $this->config =& get_config();
        $base_url = $this->config['base_url'];

        $_SESSION['error_message'] = 'Error message';
        header("location: ".$base_url.'error.html');
        exit;
    }
}

Now Error controller will be your error page, where the page will be redirected for 404 error.

18
2/23/2010 2:38:14 PM

Custom 404 page is create by using the following 3 steps,

Step 1: First open routes.php in application/config and set a custom controller name,

$route['404_override'] = 'my404'; //my404 is class name. 

Step 2: Create a new controller and write the following code in it. The code is very easy to understand. So I am not going to explain it here,

    <?php 
class my404 extends CI_Controller 
{
    public function __construct() 
    {
        parent::__construct(); 
    } 

    public function index() 
    { 
        $this->output->set_status_header('404'); 
        $data['content'] = 'error_404'; // View name 
        $this->load->view('index',$data);//loading in my template 
    } 
    } 
    ?>

Step 3: Create a view file with name 'error_404.php' with your custom message.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon