【问题标题】:know when data chunk transfer is closed知道数据块传输何时关闭
【发布时间】:2014-01-27 16:56:57
【问题描述】:

当客户端关闭数据传输时,我如何在我的 php 代码中知道?

我在 stackoverflow 上找到了这段代码(如下),但我想在客户端关闭窗口时将文本写入文件...

<?php
        header('Content-Encoding', 'chunked');
        header('Transfer-Encoding', 'chunked');
        header('Content-Type', 'text/html');
        header('Connection', 'keep-alive');

        ob_flush();
        flush();

        $p = "";  //padding
        for ($i=0; $i < 1024; $i++) { 
            $p .= " ";
        };
        echo $p;

        ob_flush();
        flush();

        for ($i = 0; $i < 10000; $i++) {
            echo "string";
            ob_flush();
            flush();
            sleep(2);
        }

?>

【问题讨论】:

    标签: php http transfer


    【解决方案1】:

    通过调用connection_aborted(),您可以了解客户端是否仍然连接。这可以在您的 for 循环中完成,如下所示。

    您还需要通过调用ignore_user_abort() 告诉PHP 在客户端断开连接后继续执行。如果您不这样做,您的脚本将在客户端断开连接后立即终止。根据您的 PHP 配置,您可能还需要使用 set_time_limit() 设置更大或无限制的时间限制。

    ignore_user_abort(true);
    
    for ($i = 0; $i < 10000; $i++) {
    
         if(connection_aborted()){
             // client disconnected, write to file here
         }
    
         echo "string";
         ob_flush();
         flush();
         sleep(2);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 2017-05-06
      • 2015-03-28
      • 2011-01-12
      • 1970-01-01
      • 2013-05-17
      相关资源
      最近更新 更多