Skip to content

Instantly share code, notes, and snippets.

@heavensloop
Last active May 13, 2022 15:04
Show Gist options
  • Save heavensloop/f0e4438b2fc00ed3d05f33e2cf938b33 to your computer and use it in GitHub Desktop.
Save heavensloop/f0e4438b2fc00ed3d05f33e2cf938b33 to your computer and use it in GitHub Desktop.
Returning a http response while continuing a process after closing the connection
<?php
public function sendEarlyResponseHeaders($res)
{
// Buffer all upcoming output...
ob_start();
// Send your response.
echo json_encode($res);
// Get the size of the output.
$size = ob_get_length();
// Disable compression (in case content length is compressed).
header("Content-Encoding: none");
header("Content-Type: application/json");
// Set the content length of the response.
header("Content-Length: {$size}");
// Close the connection.
header("Connection: close");
// Flush all output.
ob_end_flush();
ob_flush();
flush();
}
@heavensloop
Copy link
Author

heavensloop commented Sep 19, 2019

In your controller, you can send the reponse like this:

<?php

$response = ["status" => "recieved", "message" => "You will receieve an email shortly"];
$this->sendEarlyResponseHeaders($response);

// Start sending the email and other processes..
AppEmail::send();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment