避免由于URL头中缺少ID而导致的错误


Avoid Errors due to missing ID in URL header

使用Codeigniter +篝火框架,我可以在我的URL传递变量。这对于GET函数都非常有效,像这样:

在我的视图文件中我得到了我的用户ID然后点击将它再次传递给控制器:

<a href="/my_team/index/<?php echo $user->member->id; ?>">Something</a>

控制器接收到ID:

public function index($id = null) {
    //do stuff with that id...
}

URL如下:

http://mysite/my_team/index/26

并且该页面上的所有内容都知道用户的ID为26并正确显示信息。

问题是,如果我手动从URL中删除这个数字,它看起来像这样:

http://mysite/my_team/index/

并在URL中留下索引,我现在得到了一大堆错误,因为网站不能从URL中获得ID。我怎样才能避免这种情况呢?也许隐藏index公共功能从URL使用。htacces或什么?

就像@CBroe在评论中说的那样。像这样:

public function index($id = null) {
   if(is_null($id)) {
      // redirect to custom error page
   }
    //do stuff with that id...
}

设置CI url路由器重定向

http://mysite/my_team/index/

到默认url,如

http://mysite/my_team/index/1

参数可以是字符串值,所以我更喜欢这种方式

public function index($id = '') {
   if($id!='') {
      // Proceed further
   }
else{
    //Redirect to a error page(that is 301 safe)
   }
}