Display a view for 404 error in CodeIgniter

2020-02-25 09:01发布

The CodeIgniter has a very simple default error 404 message:

404 Page Not Found
The page you requested was not found.

Instead of using this error message on totally blank page, I want to wrap this message in between my header and footer view, so that the error message have similar look to the other pages.

For that purpose, I have created an error view? For example:

my404_view.php

<? $this->load->view('header'); ?>
404 Page Not Found
The page you requested was not found.
<? $this->load->view('footer'); ?>

Now, How can I use this my404_view.php as a default view to display 404 messages instead of using the CodeIgniter default error message.

3条回答
姐就是有狂的资本
2楼-- · 2020-02-25 09:16

You should change your routes.php. For example:

in application/config/routes.php

$route['404_override'] = 'welcome/_404';

in application/controllers/welcome.php

function _404(){
    $this->load->view("my404_view");
}

And this should be sufficient in the current version of CI.

查看更多
该账号已被封号
3楼-- · 2020-02-25 09:29

Including headers and footers in the default error 404 page seems to be a common problem for CodeIgniter users. I would like to add this link: Simon Emms's comments at http://www.simonemms.com/2011/05/06/codeigniters-404-override-problem/ because he describes the problem so clearly. I have tried the suggestions at http://maestric.com/doc/php/codeigniter_404 and played around with Simon Emms's ideas, and others, but just can't implement them. I'm a bit of a novice at PHP and CodeIgniter, so that might be because of ignorance. That said, it is difficult to ensure that you put the suggested subclasses in the right places and configure, for instance, routes.php correctly. After 3 days of trying the various rather complicated ideas, it occurred to me that I could just use an include statement in the default error 404 page. The only difficulty was figuring out the path to pass to the include statement. In /system/core/Exceptions.php line 146, I found the CodeIgniter developers use APPPATH. You then just have to append the path to the header and footer pages you want to include. My new default error 404 page now looks like this:

<?php
include APPPATH.'/views/templates/header.php';
?>
<div id="container">
    <h1><?php echo $heading; ?></h1>
    <?php echo $message; ?>
</div>
<?php
include APPPATH.'/views/templates/footer.php';
?>

This seems a much easier solution to me than trying to change the core classes in CodeIgniter.

查看更多
登录 后发表回答