Continue php script after connection close

后端 未结 4 1200
南旧
南旧 2020-12-30 19:09

I am trying to continue a PHP Script after the page/connection is closed.

Users will POLL the script in every 1 hour, I want to return some json output and want to c

4条回答
  •  执笔经年
    2020-12-30 19:34

    First, don't use space after Connection and before : it should be Header: value not Header : value. Second, Connection: close don't force browser to stop getting current response and display blank page. Here http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html chapter 14.10 it states: Connection: close in either the request or the response header fields indicates that the connection SHOULD NOT be considered 'persistent' (section 8.1) after the current request/response is complete

    So how can you try if your code works:

    ignore_user_abort();
    header("Content-Type: text/plain; charset=UTF-8");
    
    // just to try show following echo immediately, working depends on server configuration
    while (@ob_end_flush()); 
    
    echo date('Y-m-d H:i:s'), PHP_EOL;
    
    echo "JSON_OUTPUT GOES HERE", PHP_EOL;
    
    sleep(10); // 10 seconds so you can close browser tab before
    
    // this file should be created after 10 seconds, even after you closed browser tab
    // also check if permissions to write to __DIR__ are set for apache.
    file_put_contents(__DIR__ . '/tmp.txt', "Text after 10 sec");
    
    exit;
    

    Open this php file in browser and after 2-3 seconds close tab (even if you don't see anything on screen), wait a little longer and check if file is created. It's working on my linux machine.

提交回复
热议问题