Codeigniter custom 404 page not found

5.7k views Asked by At

I have already created custom 404 error page by changing the route in route.php

$route['404_override'] = 'error_404/index';

where error_404 is controller and this controller redirects to my custom 404 view page

<?php
ob_start();
class error_404 extends Front_Controller {

    function __construct()
    {
        parent::__construct();

        //make sure we're not always behind ssl
        remove_ssl();
    }

    function index()
    {   
        $this->load->view('404.php', '');
    }
}

it few cases it does not load 404 error page and throws "Content Encoding Error" in those pages. I have searched in this portal tried the following options

1) In my Libraries creating a file name MY_Exceptions and extend it with CI_Exceptions

2) Redirecting in error_404.php to my custom page by adding header function

3) changing config $config['compress_output']=FALSE

4) adding ob_flush(); in system/core/Output.php

2 & 3 works but I do not want to change $config['compress_output'] nor want to make major changes in error_404.php which CI default redirects to...Any other way out?

2

There are 2 answers

6
turntwo On

How about you just render the page in your MY_Exception. I'm not sure if this will work for you but it always has for me,

$route['404_override'] = 'error_404/index';

In the controller:

<?php

class error_404 extends CI_Controller {

    function __construct()
    {
        parent::__construct();
    }

    function index()
    {   
        show_404();
    }
}

application/core/MY_Exceptions

<?php

class MY_Exceptions extends CI_Exceptions {

    /**
     * render the 404 page
     *
     */
    public function show_404($page = "", $doLogError = TRUE)
    {
        include APPPATH . 'config/routes.php';

        if($page === ""){
            $page = $_SERVER['REQUEST_URI'];
        }

        if ($doLogError){
            log_message('error', '404 Page Not Found --> '.$page);
        }

        if(!empty($route['404_override']) ){
            $CI =& get_instance();
            $CI->load->view('error/404');
            echo $CI->output->get_output();
            exit;
        } 
        else {
            $heading = "404 Page Not Found";
            $message = "The page you requested was not found.";
            echo $this->show_error($heading, $message, 'error_404', 404);
            exit;
        }
    }

} 

This way I can call show_404() in any another controller if I want to show that a particular resource is unavailable.

2
John On

May be you have to set header!

public function index()
{
    $this->output->set_status_header('404');
    $this->load->view('404.php');//loading in my template
}