知道数据块传输何时关闭

时间:2014-01-27 16:56:57

标签: php http transfer

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

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

<?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);
        }

?>

1 个答案:

答案 0 :(得分:0)

通过致电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);
}