我遇到了关于直接访问函数的问题:例如我有这个代码:
控制器用户
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等。
答案 0 :(得分:2)
CI控制器函数始终必须能够处理用户输入(即url段),这意味着任何人都可以输入他们想要的任何内容并发出请求。你不能阻止它。最佳做法是:
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的_underscore()
命名(使其无法从URL中访问)。如果您愿意,您仍然可以使用其他方法调用该函数,如:
function index() {
if ($this->input->post('add_car')
{
// Call the private "_add" method
$this->_add();
}
// Load index view
}
所以长话短说:你无法阻止请求被发出,你只能在请求无效时决定该做什么。
答案 1 :(得分:0)
在要隐藏的函数名称前添加下划线:
function _details($id){
//a function where 1 car can be viewed in detail..
}
function add(){
//function to add car
}