发送响应并继续执行脚本 - PHP [重复]

Posted

技术标签:

【中文标题】发送响应并继续执行脚本 - PHP [重复]【英文标题】:Send response and continue executing script - PHP [duplicate] 【发布时间】:2018-03-24 08:13:52 【问题描述】:

我想知道是否可以在完成执行脚本之前向请求发送响应?

例如,服务器 A 正在向我的服务器 B 发送请求(server2server 请求)。除了向服务器 A 发送响应之外,我还需要对其他 API 执行一些 curl 请求并将一些数据保存到 DB。 我不想强制服务器 A 等待这个额外的任务,因为它可能会导致连接超时。

有一种使用队列(如 Beanstalkd)的解决方法,但我想知道是否可以按照我描述的方式以及使用这种方法是否存在任何危险。

【问题讨论】:

可以,使用队列系统 【参考方案1】:

你可以试试这样的。

ignore_user_abort(true);
set_time_limit(0);

ob_start();
// do initial processing here
echo $response; // send the response
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
ob_flush();
flush();

// now the request is sent to the browser, but the script is still running
// so, you can continue...

【讨论】:

以上是关于发送响应并继续执行脚本 - PHP [重复]的主要内容,如果未能解决你的问题,请参考以下文章