Open In App

How to create custom 404 page in CodeIgniter ?

Last Updated : 31 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

We often see the 404 error page while using websites. This error page will encounter only when we navigate to a broken link. In CodeIgniter, it is possible to create a custom 404 page to change the look of the 404 page. So in this article, we will look into how to create the custom 404 error page. 

 

In order to create a custom 404 error page, we need to do three steps:

  1. View
  2. Controller
  3. Route

View: In the View section, we create an error404.php page in the application/views/directory which will be displayed when any problem occurs while navigating between URLs. The standard error page doesn’t contain any CSS. In order to add styles and make the 404 Error page more attractive, a custom page can be created. Below is the HTML code that also consists of Internal CSS.

error404.php




< !doctype html>
<html>
  
<head>
    <title>Page Not Found 404 Error</title>
    <style>
        body {
            background - color: green;
            color: white;
        }
  
        div {
            position: absolute;
            text-align: center;
            width: 400px;
            height: 300px;
            top: 45%;
            left: 50%;
            margin: -100px 0 0 -200px;
        }
  
        h1,
        h2 {
            text - align: center;
        }
  
        h1 {
            font - size: 50px;
            margin-bottom: 10px;
            border-bottom: 1px solid white;
        }
    </style>
</head>
  
<body>
    <div>
        <h1>404</h1>
        <h2>Page not found</h2>
    </div>
</body>
  
</html>


Controller: In Controller phase, we create a customError404.php in application/controllers/directory. Inside the ccustomError404.php code, in index() method load error404 view and also execute $this->output->set_status_header(‘404’). Let’s look at the code of controller.

customError404.php




<? php
defined('BASEPATH') OR exit('No direct script access allowed');
class CustomError404 extends CI_Controller {
    public function __construct() {
        parent:: __construct();
        $this -> load -> helper('url');
    }
  
    public function index() {
        $this -> output -> set_status_header('404');
        $this -> load -> view('error404');
    }
}


Route: In this step, we need to edit the route.php file which is present in the application/config/ directory and assign the custom controller customError404.php to $route[‘404_override’].

Steps:

  1. Open application/config/route.php
  2. Edit it to $route[‘404_override’]=’customError404.php’;

Output: The custom 404 Error page we created in this article is look like:

404 Error Page



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads