How do I close a client connection early, while continuing to run my code?
You are encountering a fundamental conflict between server-side execution flow and HTTP protocol behavior. The core issue is that header("Connection: Close") instructs the server to terminate the TCP connection immediately after sending the response headers. However, your PHP script continues executing subsequent linesâlike the long-running mail() functionâbecause the Zend Engine does not stop running just because a header was sent.
When you attempt to send a JSON or HTML payload and then signal the client to disconnect while the server still processes background logic, the server will likely hang waiting for output buffering to flush or simply block the main thread until the mail() function completes. If you rely on the standard Connection: Close header in this scenario, you are effectively telling the browser, "Stop receiving data," but the PHP interpreter hasn't heard that command yet; it's still stuck executing your script.
To achieve a response that appears instantly to the client while the server continues processing, you must decouple the HTTP response stream from the application logic execution flow. This requires specific handling of output buffering and stream status flags.
The standard approach involves ensuring that no further data is written to the output buffer after the initial response is sent. If you are using PHP's internal output buffering (which is often enabled by default), you must explicitly flush the buffers before sending the "close" signal, or disable them entirely for the duration of the long task.
Here is a pattern that allows the server to send an immediate acknowledgment and then proceed with background work:
<?php
// Ensure no output buffering interferes with the immediate response
ob_implicit_flush(true);
ob_end_flush(); // Flush any existing buffer immediately
echo "<pre>We'll email you as soon as this is done.</pre>";
flush(); // Force the browser to render what it has so far
// Signal the client that we are done sending headers and can disconnect
header("Connection: close");
header("Content-Type: text/html; charset=utf-8");
// At this point, the server sends the response and prepares to close the socket.
// However, the script continues running.
// The tricky part is ensuring the mail() function doesn't try to write more output.
// Perform the long-running task
mail('dude@example.com', 'okay I\'m done', 'Yup, all done.');
// If you want the server to actually close the connection immediately after this,
// you must ensure no further output is generated.
// In many configurations, if no more output is produced and the buffer is empty,
// the socket closes naturally once PHP finishes.
?>
The critical realization here is that header("Connection: Close") does not trigger an immediate exit from the PHP script; it merely sets a flag in the HTTP headers to be sent with the current response. The PHP engine continues executing until the script ends or hits an error. If your mail() function takes ten seconds, those ten seconds are spent on the server-side worker process.
The browser receives the initial HTML immediately because you flushed the output buffer. Once the connection is marked for closing and no new data is appended to the response stream, the HTTP transport layer tears down the connection. The PHP script, however, keeps running in the background until the mail() function completes.
This pattern works best when your server environment supports persistent connections or when you are specifically targeting a client that respects the Connection: Close directive immediately after flushing output. If you are using frameworks like Laravel, ensure that middleware does not interfere with output buffering or automatically close connections before your logic finishes.
A common pitfall is assuming that the script will stop running once the connection closes. The PHP process remains active until the final line of code executes. If the mail() function attempts to write additional headers or output after the connection is logically "closed" for HTTP purposes, you might encounter errors depending on how your web server (Apache/Nginx) handles the socket state.
In modern architectures, this manual flushing approach is often superseded by sending a lightweight response and then using asynchronous queues or worker processes to handle the heavy lifting, ensuring the main request thread returns immediately without needing to manage connection states manually.