PHP 提前关闭连接。如果完成任何输出,脚本将挂起

标签 php

我提前关闭了与客户端的连接:

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/

相关文章:

php - 使用 PHP 在 Ejabberd 上进行 XMPP SASL 身份验证

php - MySql Select查询(JOIN上限制选择)

php - 5 次尝试记录页面

php - 使用 PHP 创建 JSON 提要以与 JQuery 一起使用

php - 创建电影调查 - PHP 问题

php - curl 多请求分割结果数组

php - 使用键数组在多维数组中设置值

php - 我可以将哪些服务器端 PDF 呈现组件与 .NET、PHP、Ruby 等一起使用?

php - 在 PHP 中获取两个查询的总数

php - Laravel 存储函数更改返回数据