发送http响应后继续处理php

发送http响应后继续处理php

我的脚本由服务器调用。从服务器收到ID_OF_MESSAGETEXT_OF_MESSAGE.

在我的脚本中,我将处理传入的文本并使用params生成响应:ANSWER_TO_IDRESPONSE_MESSAGE.

问题是我会给你回复"ID_OF_MESSAGE",但是在收到http响应200之后,发送消息给我的服务器将把他的消息设置为发送给我(这意味着我可以向他发送ID的响应)。

解决方案之一是将消息保存到数据库中,并使一些cron每分钟运行一次,但我需要立即生成响应消息。

有什么解决方案吗?如何将HTTP响应200发送到服务器,然后再继续执行php脚本?

非常感谢


至尊宝的传说
浏览 516回答 3
3回答

慕尼黑5688855

是。你可以这样做:ignore_user_abort(true);set_time_limit(0);ob_start();// do initial processing hereecho $response; // send the responseheader('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...

哔哔one

我在这里看到了很多建议ignore_user_abort(true);但是这个代码是不必要的。所有这一切都是确保您的脚本在用户中止时在发送响应之前继续执行(通过关闭他们的浏览器或按转义来停止请求)。但这不是你想要的。您要求在发送响应后继续执行。你所需要的只是以下几点:    // Buffer all upcoming output...     ob_start();     // Send your response.     echo "Here be response";     // Get the size of the output.     $size = ob_get_length();     // Disable compression (in case content length is compressed).     header("Content-Encoding: none");     // Set the content length of the response.     header("Content-Length: {$size}");     // Close the connection.     header("Connection: close");     // Flush all output.     ob_end_flush();     ob_flush();     flush();     // Close current session (if it exists).     if(session_id()) session_write_close();     // Start your background work here.     ...如果您担心后台工作会比PHP的默认脚本执行时间长,那么坚持set_time_limit(0);在顶端。

GCT1015

我在这个问题上花了几个小时,我附带了一个在Apache和Nginx上工作的函数:/**  * respondOK.  */protected function respondOK(){     // check if fastcgi_finish_request is callable     if (is_callable('fastcgi_finish_request')) {         /*          * This works in Nginx but the next approach not          */         session_write_close();         fastcgi_finish_request();         return;     }     ignore_user_abort(true);     ob_start();     $serverProtocole = filter_input(INPUT_SERVER, 'SERVER_PROTOCOL', FILTER_SANITIZE_STRING);     header($serverProtocole.' 200 OK');     header('Content-Encoding: none');     header('Content-Length: '.ob_get_length());     header('Connection: close');     ob_end_flush();     ob_flush();     flush();}您可以在长时间处理之前调用此函数。
打开App,查看更多内容
随时随地看视频慕课网APP