This query addresses the challenge of closing a connection before completing a PHP script. The goal is to initiate a lengthy process through AJAX but return a response indicating its commencement without waiting for the PHP script to finish.
According to the PHP manual, terminating a TCP connection without ending the PHP script involves more than just sending a "close" header. User-note #71172 (November 2006) provides a comprehensive solution:
<?php 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(); // Do processing here sleep(30); echo('Text user will never see'); ?>
For the solution to work, it is crucial to disable output buffering, purge the buffer, and then send header information. While sending a "close" header is necessary, it is not sufficient to close the connection immediately.
Subsequent user-notes #89177 (February 2009) and #93441 (September 2009) provide additional insights into connection handling and help clarify the nuances of early connection closure in PHP.
The above is the detailed content of How Can I Close a PHP Connection Early After Initiating a Long-Running Process via AJAX?. For more information, please follow other related articles on the PHP Chinese website!