【问题标题】:CodeIgniter 3 URI Paramaters and 404 PagesCodeIgniter 3 URI 参数和 404 页面
【发布时间】:2018-11-30 22:47:18
【问题描述】:

我有一个名为 Collection 的类,它有两个名为 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 错误吗?

感谢任何建议。

【问题讨论】:

  • 您给出的参数被视为您正在访问的方法的参数,这意味着如果您像这样example.com/collection/cars/something 给出,您可以在您的cars 方法中访问这个参数像这样public function cars($param){ echo $param;}跨度>
  • 不知道为什么你觉得这应该是 404,因为参数被忽略并且控制器/方法做了它应该做的事情。但是如果 404 是你想要的,@pradeep 已经给了你一个很好的答案。
  • 如果我访问 URI example.com/collection/cars/something/blah/blah,我应该不会看到 404 页面,因为 URI 不存在?

标签: php codeigniter http-status-code-404 codeigniter-3


【解决方案1】:

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

您给出的段被视为您正在访问的方法的参数,这意味着如果您这样给出

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

【讨论】:

  • 感谢您的回答和解释。我仍然看不到我需要做什么才能获得 404 页面?基本上,如果/cars/ 之后有任何其他 URI 参数,我希望查看 404 页面。
  • 我已经更新了我的答案,请参见上次更新部分中基于细分的条件
猜你喜欢
  • 2019-08-02
  • 1970-01-01
  • 2012-06-02
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 2020-07-14
相关资源
最近更新 更多