CodeIgniter 2.1 issue with show_404() and 404_override

后端 未结 4 1587
抹茶落季
抹茶落季 2020-12-08 15:51

I have been working with CodeIgniter for quite a while now and I\'m currently doing a project for a client that would like a custom 404 pag

4条回答
  •  被撕碎了的回忆
    2020-12-08 16:36

    I was searching for the same thing, but found quite long solutions like creating own error controller and exception class or simply redirecting to 404 page (which isn't good semantically).

    So I did bit research on how CI calls '404_override' route internally. Here's the solution I came up with:

    // Override show_404 method
    function show_404(){
        // Load Router and Core classes.
        $RTR =& load_class('Router', 'core');
    
        // Get class and method for 404 from routes.php
        $x = explode('/', $RTR->routes['404_override']);
        $class = $x[0];
        $method = (isset($x[1]) ? $x[1] : 'index');
    
        // Get current class and method for callback
        $callback_class = $RTR->fetch_class();
        $callback_method = $RTR->fetch_method();
        // Can also log here, using callback class and method.
    
        // Create object for callback
        $CI = new $callback_class;
        call_user_func_array(array(&$CI, $method), array_slice(array($class,$method), 2));
    } // End!
    

    Add this function in system/core/CodeIgniter.php file. This will override show_404 function. You can call it from your controllers and it will call '404_override' route given in routes.php file.

提交回复
热议问题