为了账号安全,请及时绑定邮箱和手机立即绑定

发送http响应后继续处理php

发送http响应后继续处理php

至尊宝的传说 2019-07-16 16:48:52
发送http响应后继续处理php我的脚本由服务器调用。从服务器收到ID_OF_MESSAGE和TEXT_OF_MESSAGE.在我的脚本中,我将处理传入的文本并使用params生成响应:ANSWER_TO_ID和RESPONSE_MESSAGE.问题是我会给你回复"ID_OF_MESSAGE",但是在收到http响应200之后,发送消息给我的服务器将把他的消息设置为发送给我(这意味着我可以向他发送ID的响应)。解决方案之一是将消息保存到数据库中,并使一些cron每分钟运行一次,但我需要立即生成响应消息。有什么解决方案吗?如何将HTTP响应200发送到服务器,然后再继续执行php脚本?非常感谢
查看完整描述

3 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞


是。你可以这样做:


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...


查看完整回答
反对 回复 2019-07-16
?
哔哔one

TA贡献1854条经验 获得超8个赞

我在这里看到了很多建议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);在顶端。


查看完整回答
反对 回复 2019-07-16
?
GCT1015

TA贡献1827条经验 获得超4个赞

我在这个问题上花了几个小时,我附带了一个在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();}

您可以在长时间处理之前调用此函数。


查看完整回答
反对 回复 2019-07-16
  • 3 回答
  • 0 关注
  • 513 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信