How do I close a connection early?

前端 未结 19 1435
情书的邮戳
情书的邮戳 2020-11-22 04:24

I\'m attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I\'d like the script to simply send a response indicating that the process has star

19条回答
  •  一生所求
    2020-11-22 04:56

    Joeri Sebrechts' answer is close, but it destroys any existing content that may be buffered before you wish to disconnect. It doesn't call ignore_user_abort properly, allowing the script to terminate prematurely. diyism's answer is good but is not generically applicable. E.g. a person may have greater or fewer output buffers that that answer does not handle, so it may simply not work in your situation and you won't know why.

    This function allows you to disconnect any time (as long as headers have not been sent yet) and retains the content you've generated so far. The extra processing time is unlimited by default.

    function disconnect_continue_processing($time_limit = null) {
        ignore_user_abort(true);
        session_write_close();
        set_time_limit((int) $time_limit);//defaults to no limit
        while (ob_get_level() > 1) {//only keep the last buffer if nested
            ob_end_flush();
        }
        $last_buffer = ob_get_level();
        $length = $last_buffer ? ob_get_length() : 0;
        header("Content-Length: $length");
        header('Connection: close');
        if ($last_buffer) {
            ob_end_flush();
        }
        flush();
    }
    

    If you need extra memory, too, allocate it before calling this function.

提交回复
热议问题