How do I close a connection early?

前端 未结 19 1403
情书的邮戳
情书的邮戳 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 05:07

    I'm on a shared host and fastcgi_finish_request is setup to exit scripts completely. I don't like the connection: close solution either. Using it forces a separate connection for subsequent requests, costing additional server resources. I read the Transfer-Encoding: cunked Wikipedia Article and learned that 0\r\n\r\n terminates a response. I haven't thoroughly tested this across browsers versions and devices, but it works on all 4 of my current browsers.

    // Disable automatic compression
    // @ini_set('zlib.output_compression', 'Off');
    // @ini_set('output_buffering', 'Off');
    // @ini_set('output_handler', '');
    // @apache_setenv('no-gzip', 1);
    
    // Chunked Transfer-Encoding & Gzip Content-Encoding
    function ob_chunked_gzhandler($buffer, $phase) {
        if (!headers_sent()) header('Transfer-Encoding: chunked');
        $buffer = ob_gzhandler($buffer, $phase);
        return dechex(strlen($buffer))."\r\n$buffer\r\n";
    }
    
    ob_start('ob_chunked_gzhandler');
    
    // First Chunk
    echo "Hello World";
    ob_flush();
    
    // Second Chunk
    echo ", Grand World";
    ob_flush();
    
    ob_end_clean();
    
    // Terminating Chunk
    echo "\x30\r\n\r\n";
    ob_flush();
    flush();
    
    // Post Processing should not be displayed
    for($i=0; $i<10; $i++) {
        print("Post-Processing");
        sleep(1);
    }
    

提交回复
热议问题