首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >发送http响应后继续处理php

发送http响应后继续处理php
EN

Stack Overflow用户
提问于 2013-03-07 22:20:02
回答 10查看 79.8K关注 0票数 123

我的脚本被服务器调用。从服务器接收ID_OF_MESSAGETEXT_OF_MESSAGE

在我的脚本中,我将处理传入的文本并生成带有参数ANSWER_TO_IDRESPONSE_MESSAGE的响应。

问题是,我正在向传入的"ID_OF_MESSAGE"发送响应,但是发送消息给我进行处理的服务器会在收到http响应200后,将他的消息设置为传递给我(这意味着我可以向他发送对该ID的响应)。

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

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

非常感谢

EN

回答 10

Stack Overflow用户

发布于 2013-03-07 22:24:42

是。您可以这样做:

代码语言:javascript
复制
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
票数 215
EN

Stack Overflow用户

发布于 2015-02-26 17:05:05

我在这里看到了很多建议使用ignore_user_abort(true);的回复,但这段代码并不是必需的。所有这些都是为了确保您的脚本在用户中止(通过关闭他们的浏览器或按Esc键停止请求)的情况下发送响应之前继续执行。但这不是你想要的。您请求在发送响应后继续执行。你所需要的就是:

代码语言:javascript
复制
// 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);放在首位。

票数 64
EN

Stack Overflow用户

发布于 2016-08-12 20:39:04

如果您正在使用FastCGI处理或PHP-FPM,您可以:

代码语言:javascript
复制
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

问题#68722:https://bugs.php.net/bug.php?id=68772

票数 42
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15273570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档