CodeIgniter displays a simple 404 error page whenever the user navigates to a broken link.
You can easily customize it and make it more user-friendly for the user.
In this tutorial, I show how you can create a custom 404 error page in CodeIgniter 3.
Contents
1. Route
Open application/config/route.php
file.
Edit –
$route['404_override'] = 'Custom404';
Here, Custom404
is the name of the controller.
2. Controller
Create a new Custom404.php
file in application/controllers/
directory.
In index()
method execute $this->output->set_status_header('404');
and load error404
view.
Completed Code
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Custom404 extends CI_Controller { public function __construct() { parent::__construct(); // load base_url $this->load->helper('url'); } public function index(){ $this->output->set_status_header('404'); $this->load->view('error404'); } }
3. View
Create a error404.php
file in application/views/
directory.
Here, I created a simple 404 error page.
Completed Code
<!doctype html> <html> <head> <title>404 Page Not Found</title> <style> body{ width: 99%; height: 100%; background-color: mediumturquoise; color: white; font-family: sans-serif; } div { position: absolute; width: 400px; height: 300px; z-index: 15; top: 45%; left: 50%; margin: -100px 0 0 -200px; text-align: center; } h1,h2{ text-align: center; } h1{ font-size: 60px; margin-bottom: 10px; border-bottom: 1px solid white; padding-bottom: 10px; } h2{ margin-bottom: 40px; } a{ margin-top:10px; text-decoration: none; padding: 10px 25px; background-color: ghostwhite; color: black; margin-top: 20px; } </style> </head> <body> <div> <h1>404</h1> <h2>Page not found</h2> <a href='<?= base_url(); ?>' >Back to Homepage</a> </div> </body> </html>
4. Output
404 Error page looks like this.
5. Conclusion
You need to create a controller from where load custom 404 view page. Assign Controller name to $route['404_override']
in route.php
.