Mor*_*eng 31 php http chunked-encoding
我搜索了这个问题,但没有答案.
我希望我的PHP脚本在chunked中生成HTTP响应(http://en.wikipedia.org/wiki/Chunked_transfer_encoding).怎么做?
更新:我明白了.我必须指定Transfer-encoding标头并刷新它.
header("Transfer-encoding: chunked");
flush();
Run Code Online (Sandbox Code Playgroud)
冲洗是必要的.否则,将生成Content-Length标头.
而且,我必须自己制作块.有了辅助功能,并不难.
function dump_chunk($chunk)
{
echo sprintf("%x\r\n", strlen($chunk));
echo $chunk;
echo "\r\n";
}
Run Code Online (Sandbox Code Playgroud)
如果您未指定内容长度标头并且发生刷新,则PHP响应将始终被分块.(这将在x字节后自动发生,只是不确切知道多少).
关心这是一个奇怪的事情.这是某种学术/学习活动还是你想要解决的现实世界问题?
这已经有点小了...如果你不介意大的asunk(0x1000八位字节左右),那么是的,PHP将会成功.
<?php
while (true) {
# output data
flush()
usleep(pow(2,18));
}
?>
Run Code Online (Sandbox Code Playgroud)
PHP将生成编号的部分等.
如果你想发送微小的块,就像你对AJAX客户端所做的那样......好吧,我把OP的问题和一些关于PHP.NET的研究结合在一起,看起来他确实是一件好事. .
$ echo -en"GET/chunked/HTTP/1.1\r \nHost:ec\r \n\r \n"| nc localhost 80
HTTP/1.1 200 OK
Date: Wed, 23 May 2012 13:03:01 GMT
Server: Apache/2.2.9 (Debian) PHP/5.3.5-1 with Suhosin-Patch mod_ssl/2.2.9 OpenSSL/0.9.8o
X-Powered-By: PHP/5.3.5-1
Transfer-encoding: chunked
Content-Type: text/html
14
Teachers have class.
50
We secure our friends not by accepting favors but by doing them.
-- Thucydides
48
Vulcans never bluff.
-- Spock, "The Doomsday Machine", stardate 4202.1
31
All kings is mostly rapscallions.
-- Mark Twain
41
Reappraisal, n.:
An abrupt change of mind after being found out.
49
He who knows, does not speak. He who speaks, does not know.
-- Lao Tsu
Run Code Online (Sandbox Code Playgroud)
它是否最终会挤出它自己的(不正确的)块数,还有待观察......但我没有看到它的迹象.
<?php
header("Transfer-encoding: chunked");
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) ob_end_flush();
ob_implicit_flush(1); flush();
function dump_chunk($chunk)
{
printf("%x\r\n%s\r\n", strlen($chunk), $chunk);
flush();
}
for (;;) {
$output = array();
exec("/usr/games/fortune", $output);
dump_chunk(implode("\n", $output));
usleep(pow(2,18));
}
?>
Run Code Online (Sandbox Code Playgroud)
截至2013年2月16日的工作样本
<?php
function dump_chunk($chunk) {
//echo sprintf("%x\r\n", strlen($chunk));
echo sprintf("\r\n");
echo $chunk;
echo "\r\n";
}
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Title</title>
</head>
<body>
<?php
ob_end_flush();
flush();
ob_flush();
for ($i = 0; $i < 5; $i++) {
sleep(1);
dump_chunk('Sending data chunk ' . ($i + 1) . ' of 1000 <br />');
flush();
ob_flush();
}
sleep(1); // needed for last animation
?>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您应该能够使用:
<?php header("Transfer-Encoding: chunked");
Run Code Online (Sandbox Code Playgroud)
但您必须确保输出符合规范。