【问题标题】:How to deny access to the method if there is no value passed, or value is invalid?如果没有传递值或值无效,如何拒绝对该方法的访问?
【发布时间】:2015-08-04 10:11:15
【问题描述】:

所以我在我的一个控制器中使用了这个方法来编辑内容:

public function edit($id){
            $data;//some data that i gather
            $this->load->view('admin/layouts/main',$data);
        }
}

如果$id 为空,我可以重定向,并显示一条消息,如下所示:

public function edit($id){
  if(empty($id)){
    redirect('admin/articles');
    //here some session variable to store message that i display later
  }
  $data;//some data that i gather
  $this->load->view('admin/layouts/main',$data);
}

例如,如果我尝试像这样访问我的方法:host.com/controller/method/id 并且如果id 为空,它将重定向我。

但是我如何检查我传递的id是否正确,并且我的数据库中有一篇真实的文章,有对应的id并且可以编辑?

附:我使用 CodeIgniter 作为框架。

【问题讨论】:

  • 像这样发送默认值public function edit($id=0){//'check if $id=0;if so return else continue) >你可以使用$id=null$id=''

标签: php codeigniter oop model-view-controller


【解决方案1】:

你可以这样做,

public function edit($id = 0){
    // setting $id zero if not passed

    // check $id is integer and > 0
    ctype_digit($id) or redirect('admin/articles');

    // check record exists in your table 
    $result = $this->db->get_where('table', array('id' => $id));

    // $result will be false if no record found
    $result or redirect('admin/articles');

    $data = array();

    // if you need that in view
    $data['id']     = $id;
    $data['result'] = $result;

    $this->load->view('admin/layouts/main',$data);
}

【讨论】:

    【解决方案2】:

    验证id 的内容(即是数字)后,您需要通过id 查询数据库。如果查询没有返回,则说明id不在数据库中,您可以重定向到articles页面。

    【讨论】:

      【解决方案3】:

      对于 id,您始终可以使用 is_integer 函数。对于文章,您所能做的就是尝试通过文章的 id 获取文章,如果找不到,则进行重定向。

      【讨论】:

        猜你喜欢
        • 2016-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-04
        • 2022-01-23
        • 2020-09-15
        • 2011-04-17
        • 1970-01-01
        相关资源
        最近更新 更多