【问题标题】:codeiginter no direct access to functionscodeigniter 不能直接访问函数
【发布时间】:2011-05-30 05:10:21
【问题描述】:

我在直接访问函数时遇到了这个问题:例如我有这个代码:

控制者用户

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 为空。我想要的只是如果用户在地址栏中键入,则可以直接访问索引。我不希望用户直接进入 myapp/users/add 等。

【问题讨论】:

  • 为什么不对 add() 进行 POST 检查?只允许 POST,您不能对其执行 GET。

标签: php codeigniter view controller


【解决方案1】:

CI 控制器函数总是必须能够处理用户输入(即 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 的 _underscore() 命名(使其无法从 url 访问)。如果您愿意,您仍然可以在其他方法中调用该函数,如下所示:

function index() {
    if ($this->input->post('add_car')
    {
        // Call the private "_add" method 
        $this->_add();
    }
    // Load index view
}

长话短说:您无法阻止发出请求,您只能决定当请求无效时该怎么做。

【讨论】:

    【解决方案2】:

    在要隐藏的函数名称前添加下划线:

    function _details($id){
    //a function where 1 car can be viewed in detail..
    }
    function add(){
    //function to add car
    }
    

    【讨论】:

    • 如果我做 _details.. 页面将返回 404 错误。找不到页面。
    • 抱歉,无法验证您的输入。
    • 是的,如果您访问任何不存在的 URL,就会出现 404 错误。当您使用下划线时,它会阻止通过 URL 访问该函数,因此您会得到 404。当您隐藏一个函数时,您希望/期望发生什么?
    猜你喜欢
    • 2013-09-19
    • 2015-09-20
    • 2014-10-05
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多