How to create a 404 page in CodeIgniter

One of the must have in CodeIgniter is a custom 404 error page.

It's really easy to do and it makes huge impact for the user.

1. Create a new Controller

Create a new controller custom404.php and fill it with the following code:

Please note this code might vary according to your application, usually you won't have to change anything.

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

    public function index()
    {
        $this
            ->output
            ->set_status_header('404');
        $this->data['content'] = 'custom404view'; // View name
        $this
            ->load
            ->view('template', $data);
    }
}
?>Code language: HTML, XML (xml)

In the code above you can see what will be our next step...

2. Create the view

Create the file custom404view.php in your views folder and fill with HTML.

3. Edit your Routes file

Last but not least, edit your /application/config/routes.php adding the following line:

$route['404_override'] = 'custom404'; // Controller nameCode language: PHP (php)

The value for this route will be the name of the controller you've created in the first step.

I hope you found this tutorial helpful 😉

Comments

  1. Line 13 of your custom404 class should be changed from:
    $this->data[‘content’] = ‘custom404view’; // View name
    to:
    $data[‘content’] = ‘custom404view’; // View name

    1. Imagino que será cosa del archivo routes. Vuelve a echarle un vistazo que esté todo bien, que se esté cargando correctamente.

      Si encuentras solución avísanos 😉

Leave a Reply

Your email address will not be published. Required fields are marked *