Codeigniter CSRF仅对一次ajax请求有效

2024-04-18

我想在 jQuery 的更改事件上将图像上传到服务器上,但使用 codeigniter csrf 我只能上传图像一次。如何使用ajax上传图像以进行多个请求。请记住,当我设置此值时

config['csrf_protection'] = FALSE;

然后我可以发送多个请求 jQuery onchange 事件,但是当 csrf_protection 为 false 时,我认为 csrf 没有优势。所以问题是如何在启用 csrf_protection 的情况下使用 ajax 发送多个请求。我的jquery代码如下

$("#avatar").change(function(){
    var link = $("#avatar").val();     
    $.ajax({
        url : "<?php echo base_url('main/test'); ?>",
        type: 'post',
        data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',"id":"hello","link":link},            
        success : function(data)
        {   
            alert(data);
        }  
    });
});

我的控制器:

public function test()
{
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = 500;
    $config['max_width'] = 260;
    $config['max_height'] = 260;
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('link')) {
        echo "error";
    } else {
        $data = array('upload_data' => $this->upload->data());
        $image_name = $data['upload_data']['file_name'];
        echo $image_name;
    }
}

在我看来,你应该尝试在每个请求中重新创建你的 csrf 令牌

尝试这个代码示例...

对于js函数

var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>',
    csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
("#avatar").change(function(){
    var link = $("#avatar").val();

    var dataJson = { [csrfName]: csrfHash, id: "hello", link: link };

    $.ajax({
        url : "<?php echo base_url('main/test'); ?>",
        type: 'post',
        data: dataJson,            
        success : function(data)
        {   
            csrfName = data.csrfName;
            csrfHash = data.csrfHash;
            alert(data.message);
        }  
    });
});

对于控制器

public function test() { 
    $config['upload_path'] = './uploads/'; 
    $config['allowed_types'] = 'gif|jpg|png'; 
    $config['max_size'] = 500; 
    $config['max_width'] = 260; 
    $config['max_height'] = 260; 

    $reponse = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash()
                )

    $this->load->library('upload', $config); 
    if (!$this->upload->do_upload('link')) { 
        $reponse['message'] = "error"; 
    } 
    else { 
        $data = array('upload_data' => $this->upload->data()); 
        $image_name = $data['upload_data']['file_name']; 
        $reponse['message'] = $image_name; 
    } 

    echo json_encode($reponse);
}

让我知道并祝你好运

Note:当有人要求您发布更多数据到问题时,不要将其发布为评论或答案,最好编辑问题本身并添加内容

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Codeigniter CSRF仅对一次ajax请求有效 的相关文章