首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP中的“Transfer-Encoding:chunked”头。“填充”是做什么用的?

PHP中的“Transfer-Encoding:chunked”头。“填充”是做什么用的?
EN

Stack Overflow用户
提问于 2012-11-26 21:35:18
回答 2查看 2.9K关注 0票数 2

正如在对上一个问题(PHP External Oauth : how to displaying a waiting message while waiting for callback (not using AJAX) )的回答中所建议的,我正在使用传输编码:分块来在执行某些任务时显示等待消息。我的第一次尝试失败了,我在这个问题“Transfer-Encoding: chunked” header in PHP中找到了解决方案。有一个1024个空格的“填充”。如果没有这个填充,它就不能工作。我用谷歌搜索了一下,但我找不到这个填充物是做什么用的。以下是示例代码(来自相关问题)。

代码语言:javascript
运行
复制
<?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);
        }

?>

有没有人能解释一下为什么它在有“填充”的情况下工作,没有“填充”就不能工作?

EN

Stack Overflow用户

发布于 2012-11-26 21:49:40

我不知道这个填充应该做什么,实际上它不应该工作(如果我在这一点上错了,有人可能会启发我)。分块编码的思想是以块的形式发送数据。每个区块由一行包含区块长度的行组成,后跟一个换行符,然后是区块的数据。一个响应可以包含您想要的任意数量的块。所以基本上包含"Hello“的3个块的响应将如下所示:

代码语言:javascript
运行
复制
5 <--- this is the length of the chunk, that is "Hello" == 5 chars
Hello  <--- This is a the actual data
<-- an empty line is between the chunks
5
Hello

5
Hello

<-- send two empty lines to end the transmission

所以我会重写成类似这样的代码:

代码语言:javascript
运行
复制
<?php
        header('Content-Encoding', 'chunked');
        header('Transfer-Encoding', 'chunked');
        header('Content-Type', 'text/html');
        header('Connection', 'keep-alive');

        ob_flush();
        flush();

        for ($i = 0; $i < 10000; $i++) {
            $string = "string";
            echo strlen($string)."\r\n"; // this is the length
            echo $string."\r\n"; // this is the date
            echo "\r\n"; // newline between chunks
            ob_flush(); // rinse and repeat
            flush();
            sleep(2);
        } 
        echo  "\r\n"; // send final empty line
        ob_flush();
        flush();

?>

上面的代码不能在任何情况下工作(例如,字符串包含换行符或非ascii编码),所以你必须根据你的用例来调整它。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13565952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档