首页 > 资讯列表 > 编程/数据库 >> PHP

php下HTTP Response中的Chunked编码实现方法

PHP 2014-12-13 16:36:04 转载来源: 网络整理/侵权必删

有时候,Web服务器生成HTTP Response是无法在Header就确定消息大小的,这时一般来说服务器将不会提供Content-Length的头信息,而采用Chunked编码动态的提供body内容的长度。 进行Chunked编码传输的HTTP Response会在消息头部设置: Transfer-Encoding: chunked 表示Content Body将用Chunked编码传输内容

有时候,Web服务器生成HTTP Response是无法在Header就确定消息大小的,这时一般来说服务器将不会提供Content-Length的头信息,而采用Chunked编码动态的提供body内容的长度。
进行Chunked编码传输的HTTP Response会在消息头部设置:
Transfer-Encoding: chunked
表示Content Body将用Chunked编码传输内容。
Chunked编码使用若干个Chunk串连而成,由一个标明长度为0的chunk标示结束。每个Chunk分为头部和正文两部分,头部内容指定下一段正文的字符总数(十六进制的数字)和数量单位(一般不写),正文部分就是指定长度的实际内容,两部分之间用回车换行(CRLF)隔开。在最后一个长度为0的Chunk中的内容是称为footer的内容,是一些附加的Header信息(通常可以直接忽略)。具体的Chunk编码格式如下:


  Chunked-Body = *chunk
         "0" CRLF
         footer
         CRLF
  chunk = chunk-size [ chunk-ext ] CRLF
       chunk-data CRLF
  hex-no-zero = <HEX excluding "0">
  chunk-size = hex-no-zero *HEX
  chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-value ] )
  chunk-ext-name = token
  chunk-ext-val = token | quoted-string
  chunk-data = chunk-size(OCTET)
  footer = *entity-header


RFC文档中的Chunked解码过程如下:

 


  length := 0
  read chunk-size, chunk-ext (if any) and CRLF
  while (chunk-size > 0) {
  read chunk-data and CRLF
  append chunk-data to entity-body
  length := length + chunk-size
  read chunk-size and CRLF
  }
  read entity-header
  while (entity-header not empty) {
  append entity-header to existing header fields
  read entity-header
  }
  Content-Length := length
  Remove "chunked" from Transfer-Encoding


最后提供一段PHP版本的chunked解码代码:

 

 


$chunk_size = (integer)hexdec(fgets( $socket_fd, 4096 ) );
while(!feof($socket_fd) && $chunk_size > 0) {
$bodyContent .= fread( $socket_fd, $chunk_size );
fread( $socket_fd, 2 ); // skip rn
$chunk_size = (integer)hexdec(fgets( $socket_fd, 4096 ) );
}

 


标签: php HTTP Response 中的 Chunked 编码 实现 方法


声明:本文内容来源自网络,文字、图片等素材版权属于原作者,平台转载素材出于传递更多信息,文章内容仅供参考与学习,切勿作为商业目的使用。如果侵害了您的合法权益,请您及时与我们联系,我们会在第一时间进行处理!我们尊重版权,也致力于保护版权,站搜网感谢您的分享!

站长搜索

http://www.adminso.com

Copyright @ 2007~2024 All Rights Reserved.

Powered By 站长搜索

打开手机扫描上面的二维码打开手机版


使用手机软件扫描微信二维码

关注我们可获取更多热点资讯

站长搜索目录系统技术支持