notes icon indicating copy to clipboard operation
notes copied to clipboard

PHP响应请求后继续运行 or Continue processing php after sending response

Open lanlin opened this issue 7 years ago • 0 comments

场景

某些时候,我们希望能在向客户端输出数据后,继续向下执行代码。 我们既不希望加大PHP配置文件中的最大执行时间,同时也不希望请求了半天没有响应。 这种情况下,我们可以用一些PHP的内置函数来解决。

方法

    function keepRunning()
    {
        @ignore_user_abort(true);
        @set_time_limit(0);

        // when running with FPM
        if (is_callable('fastcgi_finish_request'))
        {
            @session_write_close();
            @fastcgi_finish_request();
            return;
        }

        $mode = php_sapi_name();
        @ob_start();

        // ignore cli & phpdbg, send close header to client (browser)
        if (!in_array($mode, ['cli', 'phpdbg']))
        {
            @header('Content-Encoding: none');
            @header('Content-Length: '. @ob_get_length());
            @header('Connection: close');
        }

        // keep in order
        // 1.ob_* buffer to normal buffer, 2.flush() normal buffer to output
        @ob_flush();
        @ob_end_flush();
        @ob_end_clean();
        @flush();
    }

    // call this method
    keepRunning();

    // ... some code ....
    // your code will continue

调用以上方法,将会冲刷并送出缓冲区的内容。 然后切断客户端连接,并继续向下执行后续代码,直至逻辑完成。

备注

该方法在大多数情况下应该都是有效的。 一些特殊情况,需要自行验证和调试。

简单的 long run 逻辑, 在不借助 swoole 等扩展或者其他额外的工具下。 用这种方式就能比较方便的解决。

lanlin avatar Sep 19 '18 07:09 lanlin