CodeIgniter 3 URI 参数和 404 页面

CodeIgniter 3 URI Paramaters and 404 Pages

我有一个名为 Collection 的 class,有两个名为 IndexCars 的方法。

在我的控制器的基本格式中,它看起来像这样;

class Collection extends CI_Controller{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
    }

    public function index(){
        $data = array(
            'title'     =>  'Index Page'
            );
        $this->load->view('template/Header');
        $this->load->view('collection/index', $data);
        $this->load->view('template/Footer');
    }

    public function cars(){
        $data = array(
            'title'     =>  'Cars Page'
            );
        $this->load->view('template/Header');
        $this->load->view('collection/list_of_cars', $data);
        $this->load->view('template/Footer');
    }
}

URI 如下所示;

example.com/collection/cars

这就是我想要的,处理 cars 方法并照常显示 list_of_cars 视图。

但是我注意到,如果我向 URL 添加另一个参数,例如

example.com/collection/cars/something

事实上,我可以根据需要添加任意数量的附加 URI 参数,而且我仍然没有收到 404 错误。

页面只是重新加载 - 它不应该显示 404 错误,因为该页面不存在吗?

如有任何建议,我们将不胜感激。

如果您的 URI 包含两个以上的段,它们将作为参数传递给您的方法。

您提供的段 is/are 被视为您正在访问的方法的参数,意味着如果您这样提供

example.com/collection/cars/something 

您可以像这样在您的汽车方法中访问此参数

public function cars($param)
{ 
   echo $param;
}

如果你这样给

example.com/collection/cars/something/testing

您可以像这样在您的汽车方法中访问此参数

public function cars($param,$param2)
{ 
   echo $param;
   echo $param2;
}

更新 :

如果您想要一些基于段的检查条件,请在您的方法中使用 $this->uri->segment(),请这样做:

if ($this->uri->segment(3) === FALSE)
{
    /*this is your error page*/
     $this->load->view('error-page');
}
else
{
        $arg = $this->uri->segment(3);
}

更多:https://www.codeigniter.com/user_guide/libraries/uri.html

一种类似的方法可以构造如下。如果有两个以上的段(即一个控制器 + 一个方法)然后参数存在所以强制 404.

if ($this->uri->total_segments() > 2)
{
     show_404(); //shows 404 page, logs the error, and ends execution
}

了解 show_404() here