如何解决codeiginter不能直接访问功能
| 我遇到有关直接访问函数的问题:例如,我有以下代码: 控制器用户function index(){
//this is my users index view,user can add,edit,delete cars
}
function details($id){
//a function where 1 car can be viewed in detail..
function add(){
//function to add car
}
现在,如果我去地址栏并输入。 localhost / myapp / users / detail,它将进入URL并回显错误,因为$ id为null。我想要的是,如果用户在地址栏中键入内容,则只能直接访问索引。我不希望用户直接进入myapp / users / add等。
解决方法
CI Controller功能始终必须能够处理用户输入(即url段),这意味着任何人都可以键入他们想要的内容并发出请求。你无法阻止。最佳做法是:
始终提供默认参数
使用URI类获取您的参数,或
func_get_args()
始终像其他任何用户输入一样,验证传递给控制器的参数的存在性和完整性。
由于它更加常见,被接受并且更易于阅读-只需确保始终提供默认值并进行验证即可。
控制器的示例:
function index() {
//this is my users index view
//user can add,edit,delete cars
}
function details($id = NULL) {
if ( ! $id) {
// No ID present,maybe redirect without message
redirect(\'users\');
}
$user = $this->user_model->get($id);
if ( ! $user) {
// ID present but no user found,redirect with error message
$this->session->set_flashdata(\'error_message\',\'User not found\');
redirect(\'users\');
}
// We found a user,load view here etc.
}
function add() {
// Check for the presence of a $_POST value
// You could also use the Form_validation lib here
if ( ! $this->input->post(\'add_car\')
{
$this->session->set_flashdata(\'error_message\',\'Invalid request\');
redirect(\'users\');
}
// Try to add the car here and always redirect from here
}
唯一的其他方法是将方法设置为私有,或按照建议使用CI的3命名(使从URL不可访问)。如果需要,您仍然可以使用其他方法来调用该函数,如下所示:
function index() {
if ($this->input->post(\'add_car\')
{
// Call the private \"_add\" method
$this->_add();
}
// Load index view
}
因此,总而言之:您不能阻止发出请求,只有在请求无效时才可以决定要做什么。
, 在要隐藏的函数名称之前添加下划线:
function _details($id){
//a function where 1 car can be viewed in detail..
}
function add(){
//function to add car
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。