CI表单中遇到错误


An Error Was Encountered in CI forms

我是Codeigniter的新手,我是从看视频中学到的,教练和我做了同样的事情,但它给了我一个错误,比如"你要求的动作是不允许的。",他对此很满意,我不知道为什么,有任何帮助。

这是我的控制器代码

public function index(){
    if($this->input->post('submit')){ 
        echo $this->input->post('first_name');
    }
    $this->load->view('forms'); 
}

这是我的视图代码

<form method="POST">
<input type="text" name="first_name" />
<input type="submit" name=submit" />
</form>

使用form_open()助手,该助手会自动添加带有CSRF值的隐藏输入。

所以你的观点应该是:

<?php echo form_open('action_url'); ?>
<input type="text" name="first_name" />
<input type="submit" name=submit" />
<?php echo form_close(); ?>

禁用CSRF保护也有效,但这是个坏主意。

您几乎是对的,您需要在表单中添加一些部分,如action,并在控制器中添加isset或empty,如

class Test_form extends CI_Controller{
    public function __construct(){
        parent::__construct();
    }
    public function index(){
        $this->load->view('form_test');
    }
    //using your example. good
    public function check_form(){
        if( isset($this->input->post('first_name', TRUE))){
            echo "success <br>$$this->input->post('fisrt_name', TRUE)";
        }
        else{
            echo "error";
        }
    }
    //using form_validation. best
    public function check_form_validation(){
        $this->load->library('form_validation');
        $this->form_validation->set_rules('first_name', 'first Name', 'trim|required|xss_clean');
        if( ! $this->form_validation->run()){
            echo "error <br>" . validation_errors();
        }
        else{
            echo "success <br>$$this->input->post('fisrt_name', TRUE)";
        }
    }
}

form_test.php

first method
<form method="post" action="<?= base_url()?>index.php/test_form/check_form">
    <input type="text" name="first_name">
    <input type="submit" value="test">
</form>
<hr>
second method
<form method="post" action="<?= base_url()?>index.php/test_form/check_form_validation">
    <input type="text" name="first_name">
    <input type="submit" value="test">
</form>