I am making some consecutives(recrusive) ajax request to a php file that writes request parameter to a file:
make_ajax(s)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if(this.readyState == 4 && this.status == 200)
{
if(s>0)
make_ajax(s-1)
}
};
xhr.open('POST','write.php?s='+s+'&string=somelongstring',true);//url + async/sync
...
xhr.send(null);
}
make_ajax(15);//start request
write.php:
file_put_contents('test.txt',$_GET['s']);
It seems that the server returns to the ajax request, before it closes the text.txt file, so the next ajax requests that is send by the recrusive get an Access Denided error because seems that the file is still open by the previrios ajax request (event it has returned)? I tested this script even with async=false but I got the same error? How I can avoid that php scripts returns before it closes the file?
NOTE: I am not using session, I just send data to server for saving in a file.
NOTE2: Here I made a simple example, in realty I am using this method for uploading file by chunks with ajax and the mozSlice method. Full code:
function uploadFileXhr(o,start_byte)
{
var total=o.size;
var chunk;
var peice=1024 * 1024;//bytes to upload at once
var end_byte=start_byte+peice;
var peice_count=end_byte/peice;
$('#debug').html(peice_count);
var is_last=(total-end_byte<=0)?1:0;
chunk=o.mozSlice(start_byte, end_byte);
var xhr = new XMLHttpRequest();//prepare xhr for upload
xhr.onreadystatechange=function()
{
if(this.readyState == 4 && this.status == 200)
{
if(is_last==0)
{
uploadFileXhr(o,end_byte);
}
}
};
xhr.open('POST','upload.php',true);//url + async/sync
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');//header
xhr.setRequestHeader('Content-Type', 'multipart/form-data');//type for upload
xhr.send(chunk);//send request of file
}
uploadFileXhr(file_input,0);//start recrusive call
upload.php:
$flag =($_GET['start']==0) ? 0:FILE_APPEND;
file_put_contents($remotePath.$add.$file_name, file_get_contents('php://input'),$flag);
NOTE3: OK actually founded a workaround to avoid that error, in upload.php script:
$flag =($_GET['start']==0) ? 0:FILE_APPEND;
$file_part=file_get_contents('php://input');
while(@file_put_contents($remotePath.$add.$file_name, $file_part,$flag)===FALSE)
{
usleep(50);
}
But still I can’t explain why i get access denided error in the first case, so waiting for comments!
Does any content at all appear in the target file(test.txt)? I.e. does it fail after the first request is made or does it fail right away? The error suggests that the server cannot write to the file. This could be either because some other process is using the file or because the web server doesn’t have write permissions to the file. Just to eliminate the obvious, make sure that your web server is actually allowed to write to the file.