gpt4 book ai didi

PHP ob_get_length 似乎返回不正确的值

转载 作者:搜寻专家 更新时间:2023-10-31 21:26:54 25 4
gpt4 key购买 nike

我有一个函数应该向客户端返回 JSON 响应,然后在不锁定客户端的情况下继续处理,这似乎工作正常,除非我添加 Content-Length header (我想这样做以确保客户端被释放)。函数是:

function replyAndCarryOn($responseText){
ignore_user_abort(true);//stop apache killing php
ob_start();//start buffer output
echo $responseText;
session_write_close();//close session file on server side to avoid blocking other requests
header("Content-Encoding: none");
header('Content-Type: application/json; charset=utf-8');
header("Content-Length: ".ob_get_length());
header("Connection: close");
ob_end_flush();
flush();
}

除了返回给浏览器的 JSON 字符串由于 Content-Length 错误而被截断外,这工作正常。例如下面的字符串

{"result":"AUTH","authList":[{"uid":"Adam","gid":"Users","authid":1}, "uid":"Admin","gid":"Admin","authid":2},{"uid":"George","gid":"Users","authid":3},{"uid":"test","gid":"Users","authid":4}],"id":"Payment"}

将显示为:

{"result":"AUTH","authList":[{"uid":"Adam","gid":"Users","authid":1},{"uid":"Admin","gid":"Admin","authid":2},{"uid":"George","gid":"Users","authid":3},{"uid":"test","gid":"Users","authid":4}],"id":"

我可以只保留 Content-Length header ,apache (2.2) 会自动添加“Transfer-Encoding:"chunked"” header ,这似乎有效,但我想深入了解为什么 ob_get_length不返回我需要的值,我知道如果启用 gzip,它会产生太长的结果,但我看到相反的值太短。

所以我想知道:

a) 我在获取内容长度方面做错了什么?

b) 遗漏它有什么问题吗?

根据@Xyv 的评论,服务器似乎在输出字符串前输出了一个换行符和八个空格,但这不包括在 ob_get_length 返回值中。令人尴尬的是,它原来是一个回车符,并且在第一个 php 标记之前以某种方式添加了八个空格。

最佳答案

为了更好的可读性,我想我会把这个作为答案发布。

也许首先捕获输出,然后制作标题,然后制作正文?

对我来说这个例子有效:

<?php
function replyAndCarryOn($responseText){
ignore_user_abort(true);//stop apache killing php
ob_flush( );
ob_start( );//start buffer output
echo $responseText;
session_write_close();//close session file on server side to avoid blocking other requests
header("Content-Encoding: none");
header('Content-Type: application/json; charset=utf-8');
header("Content-Length: ".ob_get_length());
header("Connection: close");
echo ob_get_flush();
flush();
}


replyAndCarryOn( '{"result":"AUTH","authList":[{"uid":"Adam","gid":"Users","authid":1}, "uid":"Admin","gid":"Admin","authid":2},{"uid":"George","gid":"Users","authid":3},{"uid":"test","gid":"Users","authid":4}],"id":"Payment"}' );
?>

更新 重要的是要知道 ob_start()应该在输出任何主体之前出现。缓冲区将丢失此数据,因此它可能不会被计算在内。我不是输出缓冲方面的专家,但确保放置 ob_start在脚本的开头,这样就很难(呃)犯任何错误。 (因此请小心在初始 <?php 之前放置空格和/或制表符)。

关于PHP ob_get_length 似乎返回不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34740364/

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