我的脚本被服务器调用。从服务器接收ID_OF_MESSAGE
和TEXT_OF_MESSAGE
。
在我的脚本中,我将处理传入的文本并生成带有参数ANSWER_TO_ID
和RESPONSE_MESSAGE
的响应。
问题是,我正在向传入的"ID_OF_MESSAGE"
发送响应,但是发送消息给我进行处理的服务器会在收到http响应200后,将他的消息设置为传递给我(这意味着我可以向他发送对该ID的响应)。
一种解决方案是将消息保存到数据库中,并制作一些cron,它将每分钟运行一次,但我需要立即生成响应消息。
有什么解决方案吗?如何发送http响应到服务器200,然后继续执行php脚本?
非常感谢
发布于 2013-03-07 22:24:42
是。您可以这样做:
ignore_user_abort(true);//not required
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();
fastcgi_finish_request();//required for PHP-FPM (PHP > 5.3.3)
// now the request is sent to the browser, but the script is still running
// so, you can continue...
die(); //a must especially if set_time_limit=0 is used and the task ends
发布于 2015-02-26 17:05:05
我在这里看到了很多建议使用ignore_user_abort(true);
的回复,但这段代码并不是必需的。所有这些都是为了确保您的脚本在用户中止(通过关闭他们的浏览器或按Esc键停止请求)的情况下发送响应之前继续执行。但这不是你想要的。您请求在发送响应后继续执行。你所需要的就是:
// 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);
放在首位。
发布于 2016-08-12 20:39:04
如果您正在使用FastCGI处理或PHP-FPM,您可以:
session_write_close(); //close the session
ignore_user_abort(true); //Prevent echo, print, and flush from killing the script
fastcgi_finish_request(); //this returns 200 to the user, and processing continues
// do desired processing ...
$expensiveCalulation = 1+1;
error_log($expensiveCalculation);
来源:https://www.php.net/manual/en/function.fastcgi-finish-request.php
https://stackoverflow.com/questions/15273570
复制相似问题