How to change an error displayed in codeigniter

2019-02-15 13:11发布

问题:

The URI you submitted has disallowed characters.

How do I intercept this error? Is their a callback_ function? This error occurs when I try to use an = in the URL. E.g. I put 1=1 -- I get this this error. Instead of the error page I want to redirect('main/cate/page');

How do I catch this error and redirect instead of displaying "An error was encountered page"

回答1:

Looks like the error is being thrown in system/core/URI.php. Luckily, you can extend core classes. Create a file in application/core called MY_URI.php and override the function:

class MY_URI extends CI_URI{
    function __construct(){
        parent::__construct();
    }
    function _filter_uri($str){
        if ($str != '' && $this->config->item('permitted_uri_chars') != '' && $this->config->item('enable_query_strings') == FALSE)
        {
            // preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards
            // compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern
            if ( ! preg_match("|^[".str_replace(array('\\-', '\-'), '-', preg_quote($this->config->item('permitted_uri_chars'), '-'))."]+$|i", $str))
            {
                redirect('main/cate/page');
            }
        }

        // Convert programatic characters to entities
        $bad    = array('$',        '(',        ')',        '%28',      '%29');
        $good   = array('$',    '(',    ')',    '(',    ')');

        return str_replace($bad, $good, $str);
    }
}


回答2:

You need to extend the CI_Exceptions file. This forum post has allot of good information around exceptions and error handling.

http://codeigniter.com/forums/viewthread/67096/

Something similiar to this override should allow you to redirect based on error code:

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
class OOR_Exceptions extends CI_Exceptions
{
    public function show_error($heading, $message, $template = '', $status_code = 500)
    {
        $ci =& get_instance();
        if (!$page = $ci->uri->uri_string()) {
            $page = 'home';
        }
        switch($status_code) {
            case 403: $heading = 'Access Forbidden'; break;
            case 404: $heading = 'Page Not Found'; break;
            case 503: $heading = 'Undergoing Maintenance'; break;
        }
        log_message('error', $status_code . ' ' . $heading . ' --> '. $page);
        if ($status_code == 404) 
        {
            redirect('/mypage');
        }
        return parent::show_error($heading, $message, 'error_general', $status_code);
    }
}

NOTE: This covers the basic question - "how to change an error displayed in codeigniter". There maybe more specific overrides for this particular error.