Search code examples
phpcodeigniteruploadifycsrf

How to get Uploadify working with Codeigniter + CSRF?


I'm trying to get Uploadify 2.1.4 to work with Codeigniter 2.1.0 and CSRF and I'm not having much luck. I have a very basic upload controller & the following code for uploadify:

$(function() {
        var cct = $.cookie('csrf_cookie_name');
        $('#uploadifyMe').uploadify({
            'uploader'       : '<?php echo site_url(); ?>js/uploadify/uploadify.swf',
            'script'         : '<?php echo site_url(); ?>upload/',
            'cancelImg'      : '<?php echo site_url(); ?>js/uploadify/cancel.png',
            'multi'          : true,
            'auto'           : false,
            'fileExt'        : '*.jpg;*.jpeg',
            'fileDesc'       : 'Image Files (JPG, JPEG)',
            'fileDataName' : 'imgData',
            'queueID'        : 'fileQueue',
            'simUploadLimit' : 1,
            'sizeLimit'   : 7340032,
            'removeCompleted': false,
            'scriptData' : { 'csrf_token_name' : cct, 'upload' : 'true' },
            'onSelectOnce'  : function(event, data) {
                $('.uploadifyProgress').addClass('progress');
                $('.uploadifyProgressBar').addClass('bar');
            },
            'onComplete' : function(e, i, f, r, d) {
                console.log(r);
            },
            'onError' : function(e, i, f, eO) {
                console.log(eO);
                if(eO.info == 500) {
                    $('#status').prop('class', 'alert alert-error').html('<a class="close" data-dismiss="alert">&times;</a><h4>Hmmm. Something gone wrong it has.</h4> Yoda has discovered that your security token has expired. This is because you have been here for longer than two hours. we cannot refresh your key automatically, please refresh the page and try again.');
                }
            }
        });
});

The problem is when I upload an image I get a HTTP 500 thrown back at me. I now know it's due to CSRF being turned on since if I turn it off it works fine.

I've tried a load of solutions to the problem. The one you can see in my code, and a one from here that clones your session data and sends it across with the CSRF key, but nothing works. I always end up with a 500 HTTP unless I turn off CSRF.

If anyone can help it would be really appreciated. I realize this question seems to get asked a lot, and it's driving me nutty. On a side note passing the CSRF along with standard AJAX requests works fine, just not with uploadify.


Solution

  • Use this code, it enables you to define an array of controller methods that are not subject to CSRF: https://github.com/EllisLab/CodeIgniter/pull/236.