简体   繁体   中英

CodeIgniter 404 page

When I enter a non existent url on my site it takes me to the 404 page that is specified by this in routes.php:

$route['404_override'] = 'page/not_found';

So the design of the page is as I have made it in the view not_found.php in the "page" directory.

However if I use this function to manually enforce a 404:

show_404();

It takes me to the default CodeIgniter 404 page with no style:

404 Page Not Found

The page you requested was not found.

How can I make it go to the same 404 page that I specified in the routes file?

All the answers here seem very outdated (as of version 2, at least) or very overkill. Here's a much simpler and manageable way, which only involves two steps:

  1. In application/config/routes.php modify the field 404_override to point to some controller:

     // Specify some controller of your choosing $route['404_override'] = 'MyCustom404Ctrl'; 
  2. Inside the controller specified in your routes.php , implement the index() method so it loads your custom error 404 view. You might also want to set some headers so the browser knows you're returning a 404 error:

     // Inside application/controllers/MyCustom404Ctrl.php class MyCustom404Ctrl extends CI_Controller { public function __construct() { parent::__construct(); } public function index(){ $this->output->set_status_header('404'); // Make sure you actually have some view file named 404.php $this->load->view('404'); } } 

Like the in-code comment mentioned, be sure there's a view file in application/views/404.php where you actually have your custom 404 page.

As a side note, some of the answers in this page suggest you modify stuff inside /system, which is a bad idea because when you update your version of CodeIgniter, you'll override your changes. The solution I'm suggesting doesn't mess with core files, which makes your application much more portable and maintainable, and update resistant.

Use the _remap() function. This allows you to do some very powerful stuff with 404 errors beyond what is normally built in - such as

  • Different 404 messages depending if the user is logged in or not!
  • Extra logging of 404 errors - you can now see what the referring person was to the 404, thus helping track down errors. This includes seeing if it was a bot (such as Google bot) - or if it was a logged in user, which user caused the 404 (so you can contact them for more information - or ban them if they are trying to guess admin routes or something)
  • Ignore certain 404 errors (such as a precomposed.png error for iPhone users).
  • Allow certain controllers to handle their own 404 errors different if you have a specific need (ie allow a blog controller to reroute to the latest blog for example)

Have all your controllers extend MY_Controller :

class MY_Controller extends CI_Controller
{
    // Remap the 404 error functions
    public function _remap($method, $params = array())
    {
        // Check if the requested route exists
        if (method_exists($this, $method))
        {
            // Method exists - so just continue as normal
            return call_user_func_array(array($this, $method), $params);
        }

        //*** If you reach here you have a 404 error - do whatever you want! ***//

        // Set status header to a 404 for SEO
        $this->output->set_status_header('404');


        // ignore 404 errors for -precomposed.png errors to save my logs and
        // stop baby jesus crying
        if ( ! (strpos($_SERVER['REQUEST_URI'], '-precomposed.png')))
        {
            // This custom 404 log error records as much information as possible
            // about the 404. This gives us alot of information to help fix it in
            // the future. You can change this as required for your needs   
            log_message('error', '404:  ***METHOD: '.var_export($method, TRUE).'  ***PARAMS: '.var_export($params, TRUE).'  ***SERVER: '.var_export($_SERVER, TRUE).' ***SESSION: '.var_export($this->session->all_userdata(), TRUE));
        }

        // Check if user is logged in or not
        if ($this->ion_auth->logged_in())
        {
            // Show 404 page for logged in users
            $this->load->view('404_logged_in');
        }
        else
        {
            // Show 404 page for people not logged in
            $this->load->view('404_normal');
        }
   }

Then in routes.php set your 404's to your main controller, to a function that DOES NOT EXIST - ie

$route['404']             = "welcome/my_404";
$route['404_override']    = 'welcome/my_404';

but there is NO my_404() function in welcome - this means ALL your 404's will go through the _remap function - so you achieve DRY and have all your 404 logic in one spot.

Its up to you if you use show_404() or just redirect('my_404') in your logic. If you use show_404() - then just modify the Exceptions class to redirect

class MY_Exceptions extends CI_Exceptions
{
    function show_404($page = '', $log_error = TRUE)
    {
         redirect('my_404');
    }
}

To change behavior of show_404 you need to modify a file from CI core ( system/Core/Common.php ), which is not very practical for feature updates.

Instead of that, you could:

  1. Redirect users to the same place controller/method as specified in $route['404_override'].

  2. You could create a custom library to handle custom 404's and use it like $libInstance->show_404();

     public function show_404() { set_status_header(404); return "404 - not found"; } 
  3. Or use views:

     public function show_404($template) { set_status_header(404); if (ob_get_level() > $this->ob_level + 1) { ob_end_flush(); } ob_start(); include(APPPATH.'views/'.$template.'.php'); $buffer = ob_get_contents(); ob_end_clean(); return $buffer; } 

If you tried the user_guide you would see that is shows the following:

show_404('page' [, 'log_error']) The function expects the string passed to it to be the file path to the page that isn't found. Note that CodeIgniter automatically shows 404 messages if controllers are not found.

So you need to pass the controller name as a first parameter. The second is for logging being enabled or disabled.

CodeIgniter comes with a default 404 error page But by using routing option of codeigniter you can easily show your custom 404 error page to your user.

To do this just go to route file of your codeigniter project and type below line

$route['404_override'] = 'error_404';

Here error_404 is a controller file to display the custom 404 error page or any other type of error page in your codeigniter project.

Create the error_404 file and copy this code into this file

class Error_404 extends CI_controller
{

  public function index()
  {
    $this->output->set_status_header('404');
            // Make sure you actually have some view file named 404.php
            $this->load->view('Error_page');
  }
}

Make Error_page view file in your CodeIgniter view folder and that's it, Type any wrong url and now you can see your custom 404 error page.

If you have any doubts then you can follow this tutorial which has step by step tutorial to create custom 404 error page in codeigniter

You need to set below code in application/config/routes.php

$route['404_override'] = 'page/not_found';

After you create one controller in application/controller named "page.php"

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class page extends CI_Controller {

    public function __construct(){
        parent::__construct();
    }

    public function not_found() {   
        $this->load->view('not_found');
    }
}

Then you can create your own design for 404 error page in application/view named "not_found.php"

<html>
 <body>
  <section>
   <div>
    <div align="center" style="margin-top:50px; margin-bottom:50px;">
     <img src="<?php echo base_url();?>images/404.jpg" /> // will be your image path.
    </div>
   </div>
  </section>
 </body>
</html>

Or

<html>
 <body>
  <section>
   <div>
    <div align="center" style="margin:0px auto;">
     <h1>OOPS!</h1>
     <h3>Sorry, an error has occured, Requested page not found!</h3>
     <h5 align="center"><a href="<?php echo base_url(); ?>">Back to Home</a></h5>
    </div>
   </div>
  </section>
 </body>
</html>

Change application/errors/error_404.php file to the page you want shown. That's the file that show_404() is showing...

*show_404('page' [, 'log_error'])

This function will display the 404 error message supplied to it using the following error template:

application/errors/error_404.php

The function expects the string passed to it to be the file path to the page that isn't found. Note that CodeIgniter automatically shows 404 messages if controllers are not found.

CodeIgniter automatically logs any show_404() calls. Setting the optional second parameter to FALSE will skip logging.*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM