How do I close a connection early?

前端 未结 19 1438
情书的邮戳
情书的邮戳 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:18

    It's necessary to send these 2 headers:

    Connection: close
    Content-Length: n (n = size of output in bytes )
    

    Since you need know the size of your output, you'll need to buffer your output, then flush it to the browser:

    // buffer all upcoming output
    ob_start();
    echo "We'll email you as soon as this is done.";
    
    // get the size of the output
    $size = ob_get_length();
    
    // send headers to tell the browser to close the connection
    header("Content-Length: $size");
    header('Connection: close');
    
    // flush all output
    ob_end_flush();
    ob_flush();
    flush();
    
    // if you're using sessions, this prevents subsequent requests
    // from hanging while the background process executes
    if (session_id()) session_write_close();
    
    /******** background process starts here ********/
    

    Also, if your web server is using automatic gzip compression on the output (ie. Apache with mod_deflate), this won't work because actual size of the output is changed, and the Content-Length is no longer accurate. Disable gzip compression the particular script.

    For more details, visit http://www.zulius.com/how-to/close-browser-connection-continue-execution

提交回复
热议问题