首页 > 解决方案 > 压缩手动关闭的连接并继续处理

问题描述

如何发送压缩响应并继续处理?

目前我的最小测试用例压缩了服务器响应,尽管它没有关闭连接:

<?php
ob_start();
echo '<style type="text/css">* {background-color: #000; color: #fff;}</style>';
echo '<p>Testing response: '.time().'.</p>';
$c = ob_get_contents();
ob_end_clean();

ob_start('ob_gzhandler');
echo $c;
$size = ob_get_length();
ob_end_flush();


// Set the content length of the response.
header("Content-Length: {$size}");

// Close the connection.
header('Connection: close');

// Flush all output.
ob_end_flush();

// Close current session (if it exists).
if (session_id()) {session_write_close();}

sleep(2);
file_put_contents('test.txt', 'testing: '.time().'; size: '.$size);
?>

标签: phpcompression

解决方案


由于 Rush 在ob_get_length 文档页面上的评论,我设法减少了代码。所有三个刷新命令都是必需的,注释掉其中任何一个都会导致页面直到 after 才加载sleep(4)。我对此进行了测试以确保连接在浏览器中关闭,被压缩,然后切换到我的文件管理器以查看几秒钟后创建的文件。

<?php
ob_start();
ob_start('ob_gzhandler');

// Send your response.
echo '<style>* {background-color: #000; color: #fff;}</style>';
echo '<p>Testing response: '.time().'.</p>';

// The ob_gzhandler one
ob_end_flush();

header('Content-Length: '.ob_get_length());

// The main one
ob_end_flush();
ob_flush();
flush();

// Close current session (if it exists).
if (session_id()) {session_write_close();}

sleep(4);
file_put_contents('test.txt', 'testing: '.time().'; size: '.$size);
?>

推荐阅读