php CodeIgniter 404 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10775688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:01:34  来源:igfitidea点击:

CodeIgniter 404 page

phpcodeigniter

提问by TK123

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:

当我在我的网站上输入一个不存在的 url 时,它会将我带到在 routes.php 中指定的 404 页面:

$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.

所以页面的设计就像我在“page”目录下的not_found.php视图中所做的那样。

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

但是,如果我使用此功能手动强制执行 404:

show_404();

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

它带我到没有样式的默认 CodeIgniter 404 页面:

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?

我怎样才能让它转到我在路由文件中指定的同一个 404 页面?

回答by rodrigo-silveira

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:

这里的所有答案似乎都非常过时(至少从第 2 版开始)或非常矫枉过正。这是一个更简单和易于管理的方法,它只涉及两个步骤:

  1. In application/config/routes.phpmodify the field 404_overrideto 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');
        }
    }
    
  1. application/config/ routes.php修改字段404_override以指向某个控制器:

    // Specify some controller of your choosing
    $route['404_override'] = 'MyCustom404Ctrl';
    
  2. 在您的 中指定的控制器中routes.php,实现该index()方法以便加载您的自定义错误 404 视图。您可能还想设置一些标题,以便浏览器知道您正在返回 404 错误:

    // 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.phpwhere you actually have your custom 404 page.

就像提到的代码注释一样,请确保application/views/404.php中有一个视图文件,您实际上在其中拥有自定义 404 页面。

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.

作为旁注,此页面中的一些答案建议您修改 /system 中的内容,这是一个坏主意,因为当您更新 CodeIgniter 版本时,您将覆盖您的更改。我建议的解决方案不会与核心文件混淆,这使您的应用程序更具可移植性和可维护性,并且具有抗更新性。

回答by Laurence

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

使用_remap()函数。这允许你做一些非常强大的东西,除了通常内置的 404 错误 - 例如

  • 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 (i.e. allow a blog controller to reroute to the latest blog for example)
  • 不同的 404 消息取决于用户是否登录!
  • 额外记录 404 错误 - 您现在可以看到推荐人对 404 的看法,从而帮助追踪错误。这包括查看它是否是机器人(例如 Google 机器人) - 或者它是否是登录用户,哪个用户导致了 404(因此您可以联系他们以获取更多信息 - 或者如果他们试图猜测管理员路线,则禁止他们或者其他的东西)
  • 忽略某些 404 错误(例如 iPhone 用户的 precomposed.png 错误)。
  • 如果您有特定需求,允许某些控制器处理自己的 404 错误(例如,允许博客控制器重新路由到最新的博客)

Have all your controllers extend MY_Controller:

让您的所有控制器都扩展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.phpset your 404's to your main controller, to a function that DOES NOT EXIST- i.e.

然后routes.php将您的 404 设置为您的主控制器,设置为不存在的功能- 即

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

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

NOmy_404()在欢迎功能-这意味着所有的你的404分的将通过_remap功能-让你实现干,把所有的404逻辑在一个地方。

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

如果您使用show_404()或仅redirect('my_404')在您的逻辑中使用,则取决于您。如果您使用show_404()- 那么只需修改 Exceptions 类以重定向

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

回答by Alexandru Guzinschi

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

要更改行为,show_404您需要从 CI 核心 ( system/Core/Common.php)修改文件,这对于功能更新来说不太实用。

Instead of that, you could:

取而代之的是,您可以:

  1. Redirectusers to the same place controller/methodas 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;
    }
    
  1. 用户重定向controller/method$route['404_override'] 中指定的相同位置。

  2. 您可以创建一个自定义库来处理自定义 404 并像这样使用它 $libInstance->show_404();

    public function show_404() {
        set_status_header(404);
    
        return "404 - not found";
    }
    
  3. 或者使用视图:

    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;
    }
    

回答by Bananenspin

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

如果您尝试使用 user_guide,您会看到显示以下内容:

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.

show_404('page' [, 'log_error']) 该函数期望传递给它的字符串是未找到页面的文件路径。请注意,如果未找到控制器,CodeIgniter 会自动显示 404 消息。

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

因此,您需要将控制器名称作为第一个参数传递。第二个用于启用或禁用日志记录。

回答by Sachin Jaiswal

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.

CodeIgniter 带有一个默认的 404 错误页面但是通过使用 codeigniter 的路由选项,您可以轻松地向您的用户显示您的自定义 404 错误页面。

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

为此,只需转到您的 codeigniter 项目的路由文件并在下面输入

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

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

这里的error_404是一个控制器文件,用于在您的 codeigniter 项目中显示自定义 404 错误页面或任何其他类型的错误页面。

Create the error_404file and copy this code into this file

创建error_404文件并将此代码复制到此文件中

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_pageview file in your CodeIgniter view folder and that's it, Type any wrong url and now you can see your custom 404 error page.

在您的 CodeIgniter 视图文件夹中制作Error_page视图文件,就是这样,输入任何错误的 url,现在您可以看到您的自定义 404 错误页面。

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

如果您有任何疑问,那么您可以按照本教程一步一步地在 codeigniter 中创建自定义 404 错误页面

回答by Shiljith MP

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

您需要在 application/config/routes.php 中设置以下代码

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

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

在名为“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"

然后您可以在名为“not_found.php”的应用程序/视图中为 404 错误页面创建自己的设计

<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>

回答by cmac

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

application/errors/error_404.php文件更改为您想要显示的页面。那show_404()是显示的文件...

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

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

此函数将使用以下错误模板显示提供给它的 404 错误消息:

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 会自动显示 404 消息。

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

CodeIgniter 会自动记录任何show_404()调用。将可选的第二个参数设置为FALSE将跳过日志记录。*