发送响应并继续执行脚本-PHP [英] Send response and continue executing script - PHP

查看:51
本文介绍了发送响应并继续执行脚本-PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering if is it possibile to send reponse to the reqeust before finishing executing script?

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

For example, there is server A that is sending request to my server B (server2server request). Beside sending response to server A, I need to do some curl reques to other apis and save some data to DB. I don't want to force server A to wait for this additional tasks, because it can timeout connection.

有一种使用队列的变通方法(例如Beanstalkd),但我想知道以我描述的方式是否有可能,使用这种方法是否有危险.

There is a workaround using queues (like Beanstalkd) but I'd like to know if it is possible in a way I described and if there are any dangers using this approach.

推荐答案

您可以尝试这样的操作.

You can try something like this.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆