运行 PHP 时,您希望它立即将 HTML 返回到浏览器,关闭连接(ish),然后继续处理......
以下内容在连接为 HTTP/1.1 时有效,但在使用Apache 2.4.25
, with mod_http2
enabled 且您拥有支持 HTTP/2 的浏览器(例如 Firefox 52 或 Chrome 57)时无效。
发生的情况Connection: close
是未发送标头。
<?php
function http_connection_close($output_html = '') {
apache_setenv('no-gzip', 1); // Disable mod_gzip or mod_deflate
ignore_user_abort(true);
// Close session (if open)
while (ob_get_level() > 0) {
$output_html = ob_get_clean() . $output_html;
}
$output_html = str_pad($output_html, 1023); // Prompt server to send packet.
$output_html .= "\n"; // For when the client is using fgets()
header('Connection: close');
header('Content-Length: ' . strlen($output_html));
echo $output_html;
flush();
}
http_connection_close('<html>...</html>');
// Do stuff...
?>
有关此问题的类似方法,请参阅:
至于为什么要connection
删除标头,该nghttp2
库的文档(由 Apache 使用)指出:
https://github.com/nghttp2/nghttp2/blob/master/doc/programmers-guide.rst
HTTP/2 prohibits connection-specific header fields. The
following header fields must not appear: "Connection"...
所以如果我们不能通过这个头告诉浏览器关闭连接,我们如何让它工作呢?
或者是否有另一种方式告诉浏览器它拥有 HTML 响应的所有内容,并且它不应该一直等待更多数据到达。