Created
January 14, 2015 21:39
Easy way to close connections to the browser and continue processing on the server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} |
Thank you @bubba-h57 and @razvanioan I had tried a variety of different approaches to get the connection to properly close on the client side, but finally with both your help it's closing.
In case this helps others in the future I'm using the following:
- Making a request from a Google Apps Script
- Ubuntu: 16.04.7
- Apache: 2.4
- PHP: 7.4.13 (cli) | 7.2.34-8 (apache)
- WordPress: 5.6.1
@razvanioan answer is perfect. Thankyou in php 7.4
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Almost perfect!
I've included a
session_write_close();
just afterset_time_limit(0);
: