Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Easy way to close connections to the browser and continue processing on the server.
<?php
/**
* Close the connection to the browser but continue processing the operation
* @param $body
*/
public function closeConnection($body, $responseCode){
// Cause we are clever and don't want the rest of the script to be bound by a timeout.
// Set to zero so no time limit is imposed from here on out.
set_time_limit(0);
// Client disconnect should NOT abort our script execution
ignore_user_abort(true);
// Clean (erase) the output buffer and turn off output buffering
// in case there was anything up in there to begin with.
ob_end_clean();
// Turn on output buffering, because ... we just turned it off ...
// if it was on.
ob_start();
echo $body;
// Return the length of the output buffer
$size = ob_get_length();
// send headers to tell the browser to close the connection
// remember, the headers must be called prior to any actual
// input being sent via our flush(es) below.
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
header("Content-Length: $size");
// Set the HTTP response code
// this is only available in PHP 5.4.0 or greater
http_response_code($responseCode);
// Flush (send) the output buffer and turn off output buffering
ob_end_flush();
// Flush (send) the output buffer
// This looks like overkill, but trust me. I know, you really don't need this
// unless you do need it, in which case, you will be glad you had it!
@ob_flush();
// Flush system output buffer
// I know, more over kill looking stuff, but this
// Flushes the system write buffers of PHP and whatever backend PHP is using
// (CGI, a web server, etc). This attempts to push current output all the way
// to the browser with a few caveats.
flush();
}
@saschaende

This comment has been minimized.

Copy link

@saschaende saschaende commented Jun 19, 2020

Thanks :)

@razvanioan

This comment has been minimized.

Copy link

@razvanioan razvanioan commented Aug 13, 2020

Almost perfect!

I've included a session_write_close(); just after set_time_limit(0);:

public function closeConnection($body, $responseCode){
    // Cause we are clever and don't want the rest of the script to be bound by a timeout.
    // Set to zero so no time limit is imposed from here on out.
    set_time_limit(0);

    // if using (u)sleep in an XHR the next requests are still hanging until sleep finishes
    session_write_close();

    // Client disconnect should NOT abort our script execution
    ignore_user_abort(true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.