Custom 404 Error page in Codeigniter

Codeigniter

Hello friends,

what is 404 error…?

The HTTP 404, 404 Not Found, 404, Page Not Found, or Server Not Found error message is a Hypertext Transfer Protocol standard response code, in computer network communications, to indicate that the client was able to communicate with a given server, but the server could not find what was requested.

We can customize 404 error page in codeigniter. By default the codeigniter 404 error page looks like,

Please follow below steps to customize 404 error in codeigniter framework.

Step 1. Create a Controller

Create a new file under application/controllers/Error_404.php, after that copy below code and paste it on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
        defined('BASEPATH') OR exit('No direct script access allowed');
        class Error_404 extends CI_Controller
        {
             public function index()
            {

                      $this->output->set_status_header('404');

                       $data['content'] = '404 Error';  // View name

                      $this->load->view('error_404', $data);
            }
       }
?>

 

Step 2: Create a view page for custom 404 error view

Create a new file under application/views/error_404.php file. You can create your own custom error page here. Here shows my custom 404 error page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
40
<!doctype html>
<html>
 <head>
     <title>Page Not Found</title>
 <style>
 body{
 width: 99%;
 height: 100%;
 background-color: #9e9e9e5c;
 color: white;
 font-family: sans-serif;
 }
 div {
 position: absolute;
 width: 400px;
 height: 300px;
 top: 45%;
 left: 50%;
 margin: -100px 0 0 -200px;
 text-align: center;
 }
 h1{
 text-align: center;
 }
 h1{
 text-align: center;
 margin-bottom: 10px;
 border-bottom: 1px solid white;
 padding-bottom: 10px;
 }
 </style>
 </head>
 <body>
 <div>
 <h1><?php echo isset($content)? $content : 'Page Not Found'; ?></h1>

 </div>
 </body>
</html>
Step 3: Configure route for 404 error page

Next step is to configure the 404 error page as our custom created 404 error page. Open routes.php page in your application/config/routes.php . Here you can find $route[‘404_override’] routes. This route will tell the Router which controller/method to use if those provided in the URL cannot be matched to a valid route. So here we need to route our custom 404 error page. Rewrite $route[‘404_override’]  as,

$route['404_override']  = 'Error_404/index'; // controller/function.

Friends please try this code for creating custom 404 error page in your php codeigniter framework.

….

Leave a Reply

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