How do I close a connection early?

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

    Here's a modification to Timbo's code that works with gzip compression.

    // buffer all upcoming output
    if(!ob_start("ob_gzhandler")){
        define('NO_GZ_BUFFER', true);
        ob_start();
    }
    echo "We'll email you as soon as this is done.";
    
    //Flush here before getting content length if ob_gzhandler was used.
    if(!defined('NO_GZ_BUFFER')){
        ob_end_flush();
    }
    
    // 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 ********/
    

提交回复
热议问题