Home > Software design >  Uploading files individually with ajax, possible race condition processing with php?
Uploading files individually with ajax, possible race condition processing with php?

Time:11-19

I have a simple form for uploading multiple files.

<form id="myform" enctype="multipart/form-data">
    <input id="files" name="files" type="file" class="form-control" multiple>
</form>

When user submits the form, I upload each file individually to track progress individually:

for (i=0; i<$('#files')[0].files.length; i  ){
    
    var file = $('#files')[0].files[i];
    
    uploadFile(file, recipient, $row);
    
}

The main part of the uploadFile() function:

// Pack the data
var data = new FormData();
data.append("file", file);


$.ajax({
    url: 'upload.php',
    type: 'POST',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    
    xhr: function(){
        var myxhr = $.ajaxSettings.xhr();
        if (myxhr.upload){
            // do more stuff
        }
        return myxhr;
    },
    

Now in my upload.php file, I was mistaken in thinking that the file would be in a POST variable but it still needs accessed through $_FILES. So my question is, if I trigger multiple uploads could I run into any race conditions where the php script reads $_FILES and it doesn't contain the file expected? Because upload.php isn't called until the file has been uploaded, so it wouldn't be aware of the current state of $_FILES would it? Or am I overthinking this?

CodePudding user response:

Just like any other HTTP request, each request is entirely separate. They won't conflict or cause each other problems (unless you launch so many simultaneously that the server simply can't cope with the demand).

A fresh instance of the PHP script is launched to deal with each AJAX request, which has its own separate instance of $_FILES to read from. The fact that you're using to AJAX to trigger the request is irrelevant - that's entirely transparent to the server: it does not know (or care) how the request was initiated.

  • Related