我提前关闭了与客户端的连接:
static public function early_close( $output )
{
ignore_user_abort(true);
echo $output;
// Disable gzip compression in apache, as it can result in this request being buffered until it is complete,
// regardless of other settings.
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', 1);
}
// 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');
header("Content-Encoding: none"); // To disable Apache compressing anything
// IF PHP-FM
// fastcgi_finish_request();
// flush all output
if( ob_get_level() > 0 )
{
ob_end_flush();
ob_get_level()? ob_flush():null;
flush();
}
// if you're using sessions, this prevents subsequent requests
// from hanging while the background process executes
if( session_id() )
{
session_write_close();
}
}
工作正常,但在此事件之后,如果某些脚本输出任何内容(通过回显或通过添加新 header ),脚本将从该点停止执行。
我试图在提前关闭然后丢弃它之后开始输出缓冲,但它不起作用:
Server::early_close();
ob_start();
heavy_work();
ob_clean();
有什么想法吗?
使用 php 5.3.x
最佳答案
执行此操作的经典代码是:
ob_end_clean();
header("Connection: close");
ignore_user_abort(); // optional ob_start();
echo ('Text the user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush(); // Strange behaviour, will not work
flush(); // Unless both are called !
// Do processing here
sleep(30);
echo('Text user will never see');
否则,如果您想进行异步调用,我建议阅读以下内容:Methods for asynchronous processes in PHP
关于PHP 提前关闭连接。如果完成任何输出,脚本将挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18401645/