有必要发送以下 2 个标头:
Connection: close
Content-Length: n (n = size of output in bytes )
由于您需要知道输出的大小,因此您需要缓冲输出,然后将其刷新到浏览器:
// buffer all upcoming output
ob_start();
echo 'We\'ll email you as soon as this is done.';
// get the size of the output
$size = ob_get_length();
// send headers to tell the browser to close the connection
header('Content-Length: '.$size);
header('Connection: close');
// flush all output
ob_end_flush();
ob_flush();
flush();
// if you're using sessions, this prevents subsequent requests
// from hanging while the background process executes
if (session_id()) {session_write_close();}
/******** background process starts here ********/
此外,如果您的Web服务器在输出上使用自动gzip压缩(即。带有mod_deflate)的Apache将不起作用,因为输出的实际大小已更改,并且内容长度不再准确。禁用特定脚本的 gzip 压缩。
有关更多详细信息,请访问 http://www.zulius.com/how-to/close-browser-connection-continue-execution