gpt4 book ai didi

php - file_put_contents 访问在多个 AJAX 请求上被拒绝(但已同步)?

转载 作者:可可西里 更新时间:2023-10-31 23:50:05 24 4
gpt4 key购买 nike

我正在向将请求参数写入文件的 php 文件发出一些连续(递归)ajax 请求:

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

写.php:

file_put_contents('test.txt',$_GET['s']);

似乎服务器在关闭 text.txt 文件之前返回到 ajax 请求,因此递归发送的下一个 ajax 请求会收到拒绝访问错误,因为似乎文件是否仍由 previrios ajax 请求打开(事件已返回)?我什至使用 async=false 测试了这个脚本,但我得到了同样的错误?如何避免 php 脚本在关闭文件之前返回?

注意:我没有使用 session ,我只是将数据发送到服务器以保存在文件中。

NOTE2:这里我做了一个简单的例子,实际上我是使用这种方法通过ajax和mozSlice方法分块上传文件。完整代码:

            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

上传.php:

$flag =($_GET['start']==0) ? 0:FILE_APPEND;
file_put_contents($remotePath.$add.$file_name, file_get_contents('php://input'),$flag);

注意 3:OK 实际上在 upload.php 脚本中找到了避免该错误的解决方法:

        $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);
}

但我仍然无法解释为什么在第一种情况下会出现访问被拒绝的错误,所以等待评论!

最佳答案

目标文件(test.txt)中是否出现任何内容? IE。它是在发出第一个请求后 失败还是立即失败?该错误表明服务器无法写入文件。这可能是因为某些其他进程正在使用该文件,或者因为 Web 服务器没有对该文件的写入权限。只是为了消除显而易见的问题,请确保您的网络服务器实际上被允许写入该文件。

关于php - file_put_contents 访问在多个 AJAX 请求上被拒绝(但已同步)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com