CodeIgniter Q & A

 

How to create a custom 404 error page in CodeIgniter?

Creating a custom 404 error page in CodeIgniter allows you to provide a user-friendly and branded error message when a page or resource is not found on your website. Here’s how you can create and set up a custom 404 error page:

 

  1. Create the Custom 404 View:

   Start by creating a new view file for your custom 404 error page. You can name it something like `custom_404.php` and place it in the `application/views` directory. Design this view to display the error message and any additional information you want to convey to users.

 

  1. Configure the Routes:

   To tell CodeIgniter to use your custom 404 view when a page is not found, you need to set up a route in the `routes.php` file located in the `application/config` directory. Open the `routes.php` file and add the following line:

  ```php

   $route['404_override'] = 'errors/custom_404';

   ```

   Here, `’errors/custom_404’` should match the controller and method you’ll create in the next step.

 

  1. Create the Controller:

   Now, you need to create a controller method that will load your custom 404 view. In your `application/controllers` directory, create a new controller or use an existing one. In the controller, create a method (e.g., `custom_404`) that loads your custom 404 view.

 ```php

   class Errors extends CI_Controller {

       public function custom_404() {

           $this->load->view('custom_404');

       }

   }

   ```

 

  1. Set up the .htaccess File (Optional):

   If you’re using Apache as your web server, you can improve the handling of 404 errors by adding the following lines to your `.htaccess` file:

```

   ErrorDocument 404 /index.php/errors/custom_404

   ```

   This directive tells Apache to redirect to your custom 404 page when a 404 error occurs.

 

  1. Test Your Custom 404 Page:

   Finally, test your custom 404 error page by accessing a non-existent URL on your website. You should see your custom error page displayed instead of the default CodeIgniter 404 page.

With these steps, you’ve successfully created a custom 404 error page in CodeIgniter. This page will provide a more user-friendly and consistent experience for visitors when they encounter missing or non-existent resources on your website.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Full Stack Systems Analyst, Proficient in CodeIgniter with extensive 5+ years experience. Strong in SQL, Git, Agile.