对分块响应进行放气的正确方法大致如下:
initialise string to hold result
for each chunk {
check that the stated chunk length equals the string length of the chunk
append the chunk data to the result variable
}
这是一个方便的 PHP 函数来为您执行此操作(已修复):
function unchunk_string ($str) {
// A string to hold the result
$result = '';
// Split input by CRLF
$parts = explode("\r\n", $str);
// These vars track the current chunk
$chunkLen = 0;
$thisChunk = '';
// Loop the data
while (($part = array_shift($parts)) !== NULL) {
if ($chunkLen) {
// Add the data to the string
// Don't forget, the data might contain a literal CRLF
$thisChunk .= $part."\r\n";
if (strlen($thisChunk) == $chunkLen) {
// Chunk is complete
$result .= $thisChunk;
$chunkLen = 0;
$thisChunk = '';
} else if (strlen($thisChunk) == $chunkLen + 2) {
// Chunk is complete, remove trailing CRLF
$result .= substr($thisChunk, 0, -2);
$chunkLen = 0;
$thisChunk = '';
} else if (strlen($thisChunk) > $chunkLen) {
// Data is malformed
return FALSE;
}
} else {
// If we are not in a chunk, get length of the new one
if ($part === '') continue;
if (!$chunkLen = hexdec($part)) break;
}
}
// Return the decoded data of FALSE if it is incomplete
return ($chunkLen) ? FALSE : $result;
}