English 中文(简体)
CodeIgniter 404页面
原标题:CodeIgniter 404 page

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

$route[ 404_override ] =  page/not_found ;

因此,页面的设计与我在“page”目录的视图not_found.php中所做的一样。

但是,如果我使用此函数手动执行404:

show_404();

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

404 Page Not Found

The page you requested was not found.

如何让它转到我在路由文件中指定的404页面?

问题回答

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

  1. application/config/routes.php中,修改字段404_override以指向某个控制器:

    // Specify some controller of your choosing
    $route[ 404_override ] =  MyCustom404Ctrl ;
    
  2. 在您的routes.php中指定的控制器内,实现index()

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

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

顺便说一句,本页中的一些答案建议您修改/system中的内容,这是一个坏主意,因为当您更新CodeIgniter版本时,您将覆盖您的更改。我建议的解决方案不会弄乱核心文件,这使您的应用程序更具可移植性、可维护性和抗更新性。

使用_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)

让您的所有控制器扩展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 );
        }
   }

然后在routes.php中将404设置为主控制器,设置为不存在的函数,即。

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

但是welcome中有my_404()函数-这意味着你的所有404都将通过_remap

如果你在逻辑中使用show_404()或只是redirect(my_404),这取决于你。如果你使用show_404(),那么只需修改Exceptions类即可重定向

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

要更改show_404的行为,您需要修改CI核心(system/core/Common.php

相反,你可以:

  1. 用户重定向到$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;
    }
    

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

要做到这一点,只需转到codeigniter项目的路由文件,并在下面的行中键入

$route[ 404_override ] =  error_404 ;

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

创建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 );
  }
}

在CodeIgniter视图文件夹中创建Error_page视图文件,仅此而已,键入任何错误的网址,现在您可以看到自定义的404错误页面。

如果您有任何疑问,可以按照以下步骤操作教程,其中包含在codeigniter中创建自定义404错误页面的分步教程

如果你尝试了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.

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

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

*show_404( page  [,  log_error ])

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

application/errors/error_404.php

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

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

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

$route[ 404_override ] =  page/not_found ;

在应用程序/控制器中创建一个名为“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 );
    }
}

然后,您可以在名为“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>

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




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...