-
-
Save teleclient/ce867a7d51b1528922de02fc7a1f0f0f to your computer and use it in GitHub Desktop.
Easy way to close connections to the browser and continue processing on the server.
This file contains 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); | |
// 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); | |
// 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.php.net/manual/en/features.connection-handling.php#71172
https://www.php.net/manual/en/features.connection-handling.php#93441