繁体   English   中英

如果没有传递值或值无效,如何拒绝对方法的访问?

[英]How to deny access to the method if there is no value passed, or value is invalid?

因此,我在一个用于编辑内容的控制器中拥有此方法:

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并且可以编辑?

PS我使用CodeIgniter作为框架。

你可以做这样的事情,

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);
}

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

验证id的内容(即数字)后,您需要通过该id查询数据库。 如果查询未返回任何内容,则表示该id不在数据库中,您可以重定向到articles页面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM