Home > Backend Development > PHP Tutorial > How Can I Close a PHP Connection Early After Initiating a Long-Running Process via AJAX?

How Can I Close a PHP Connection Early After Initiating a Long-Running Process via AJAX?

DDD
Release: 2024-12-29 07:06:09
Original
370 people have browsed it

How Can I Close a PHP Connection Early After Initiating a Long-Running Process via AJAX?

Closing a Connection Early

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');
?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template