UPDATE
处理这种情况的方法是输出缓冲和适当的HTTP头的组合.
HTTP/1.1 defines the “close” connection option for the sender to
signal that the connection will be closed after completion of the
response.
因此,如果我们传递除了Connection:close之外的HTTP Content-Length标头,浏览器知道在收到指定的响应长度后关闭连接:
>缓冲所有脚本输出,以便保留发送标头的功能
>获得完整的输出数据后,将相应的标头发送到客户端
>继续处理…但不要尝试发送输出,否则您将收到错误,因为已发送标题.
另外,请注意,如果处理过多,可以在Web服务器SAPI中遇到脚本执行时间限制.最后,您应该告诉PHP使用ignore_user_abort()忽略此特定脚本中的“用户中止”,因为浏览器将因您正在执行的操作而关闭连接,并且您希望PHP继续处理.
ignore_user_abort();
ob_start();
// do stuff, generate output
// get size of the content
$length = ob_get_length();
// tell client to close the connection after $length bytes received
header('Connection: close');
header("Content-Length: $length");
// flush all output
ob_end_flush();
ob_flush();
flush();
// close session if you have one ...
// continue your processing tasks ...
?>
或者,为什么不开始输出缓冲?然后,您可以捕获将要发送的所有输出,然后在您确实想要对其执行任何操作时稍后决定.
echo 'before output buffering';
ob_start();
echo 'after output buffering';
$output = ob_get_contents();
// script's only output to this point will be 'before output buffering'
// I changed my mind, send the output ...
ob_end_flush();
?>