How to create custom 404 error handler in Code Igniter

If you have ever coded in Code Igniter then you may have come across the 404 error page which is displayed by default when a page requested does not exist. For those who have not seen or do not remember can see below

Code Igniter Default 404 Error Page

Even though the page displays its intended message correctly it does not look good when you are implementing on a company/professional website. The MVC framework does provide a work around to customize the 404 error page as you require.

Follow the steps below and you will have your own 404 error page running in no time:

1. First create your 404 controller. You can name it anything. I chose the name “Custom404”. Save the file as Custom404.php

2. Open that file and insert the following code

        $data['title'] = '404 Error';
        $data['content'] = 'Sorry! The page in question does not exist';

        $this->load->view('404', $data);		

3. Now create a new file by the name of 404.php and save it in the application/views folder

Error 404

4. For the final step you need to inform Code Igniter that you are going to override its 404 error mechanism and will be displaying your own page instead. For this purpose open the application/config/routes.php file. There you will see the following line

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

Change the above line to as follows

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

The above line will now tell Code Igniter to display your custom 404 error file instead of the default 404 error file.

Hope the above helped.

If you would like to download the code for the above files please download custom404-php and 404-php

Be the first to comment

Leave a Reply