How do I close a connection early?

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

    TL;DR Answer:

    ignore_user_abort(true); //Safety measure so that the user doesn't stop the script too early.
    
    $content = 'Hello World!'; //The content that will be sent to the browser.
    
    header('Content-Length: ' . strlen($content)); //The browser will close the connection when the size of the content reaches "Content-Length", in this case, immediately.
    
    ob_start(); //Content past this point...
    
    echo $content;
    
    //...will be sent to the browser (the output buffer gets flushed) when this code executes.
    ob_end_flush();
    ob_flush();
    flush();
    
    if(session_id())
    {
        session_write_close(); //Closes writing to the output buffer.
    }
    
    //Anything past this point will be ran without involving the browser.
    

    Function Answer:

    ignore_user_abort(true);
    
    function sendAndAbort($content)
    {
        header('Content-Length: ' . strlen($content));
    
        ob_start();
    
        echo $content;
    
        ob_end_flush();
        ob_flush();
        flush();
    }
    
    sendAndAbort('Hello World!');
    
    //Anything past this point will be ran without involving the browser.
    

提交回复
热议问题