How to decode / inflate a gzip gated string?

After executing the gzip deflate request in PHP, I get a deflated string in offset pieces that looks like this

The example is significantly shortened to display the format:

00001B4E ¾"kŒj…Øæ'ìÑ«F1ìÊ`+ƒQì¹UÜjùJƒZ\µy¡ÓUžGr‡J&=KLËÙÍ~=ÍkR 0000102F ñÞœÞôÎ'üo[¾"+'Ñ8#à»0±R-4VÕ'n›êˆÍ.MCŽ…ÏÖr¿3M—èßñ°r¡\+ 00000000 

I can't inflate this, apparently due to the fragmented format. I can confirm that the data is not corrupted after manually deleting offsets using the Hex editor and reading the gzip archive. I am wondering if there is a suitable method for analyzing this chunked gzip deflated response to a readable string?

I could separate these offsets and concatenate the data in one line to call gzinflate, but there seems to be an easier way.

+7
source share
2 answers

The correct method to smooth out a fragmented response is something like this:

 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 } 

Here's a handy PHP function for this ( FIXED ):

 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; } 
+9
source

To decode a string, use gzinflate , Zend_Http_Client lib will help to do such common tasks, use them, Refer the code Zend_Http_Response , if you need to do it yourself

0
source

All Articles