Sometimes, the Web server cannot determine the message size in the Header when generating HTTPResponse. in this case, the server generally does not provide the Content-Length Header information, the Chunked encoding is used to dynamically provide the length of the body content. HTTP Response for Chunked encoding transmission will be set in the message header:
Transfer-Encoding: chunked
Indicates that the Content Body will be transmitted using Chunked encoding.
Chunked encoding is composed of several chunks, which end with a Chunk with a length of 0. Each Chunk is divided into two parts: the header and the body. the content of the header specifies the total number of characters (hexadecimal numbers) and the number Unit (generally not written) of the next body ), the body is the actual content of the specified length, and the two parts are separated by carriage return and line feed (CRLF. In the last Chunk with a length of 0, the content is called footer, which is some additional Header information (which can be ignored directly ). The specific Chunk encoding format is as follows:
The code is as follows:
Chunked-Body = * chunk
"0" CRLF
Footer
CRLF
Chunk = chunk-size [chunk-ext] CRLF
Chunk-data CRLF
Hex-no-zero =
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
The Chunked decoding process in RFC is as follows:
The code is as follows:
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
Finally, a chunked decoding code for PHP is provided:
The code is as follows:
$ 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 \ r \ n
$ Chunk_size = (integer) hexdec (fgets ($ socket_fd, 4096 ));
}