How to close a connection early with PHP?

Spread the love

Sometimes, we want to close a connection early with PHP.

In this article, we’ll look at how to close a connection early with PHP.

How to close a connection early with PHP?

To close a connection early with PHP, we call ob_end_flush and flush.

For instance, we write

ob_end_clean();
header("Connection: close");
ignore_user_abort(true);
ob_start();
echo "Text the user will see";
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();

sleep(30);
echo "Text user will never see";

to call ob_end_flush and flush together to end the TCP connection without ending the PHP script.

Then we run sleep(30); after the connection has ended.

Conclusion

To close a connection early with PHP, we call ob_end_flush and flush.

Leave a Reply

Your email address will not be published.