Peter
Peter

Reputation: 1444

Use zlib inflate() in c++ to decompress via PHP ZLIB_ENCODING_RAW encoded data

When I compress a string in PHP with encoding ZLIB_ENCODING_DEFLATE and output the hex data, I can convert this back to the original string using zlib deflate() in a c++ project.

Per the example here ( https://www.php.net/manual/en/function.zlib-encode.php ) :

<?php
$str = 'hello world';
$enc = zlib_encode($str, ZLIB_ENCODING_DEFLATE);
echo bin2hex($enc);
?>

in c++, after having converted the hex string to binary data first: (simplified code)

z_stream d_stream;

d_stream.zalloc = (alloc_func)0 ;
d_stream.zfree  = (free_func)0 ;
d_stream.opaque = (voidpf)0 

d_stream.next_in  = InBuffer ;
d_stream.avail_in = InBufferLen ;
d_stream.next_out = OutBuffer ;
d_stream.avail_out = OutBufferLen ;

int err = inflateInit(&d_stream) ;

while (err == Z_OK)
    err = inflate(&d_stream, Z_NO_FLUSH);

err = inflateEnd(&d_stream);

OutBuffer contains "hello world" again

I was wondering if zlib inflate() also decompresses the via PHP generated zlib_encode($str, ZLIB_ENCODING_RAW); raw data ?

From the zlib documentation I think not:

The deflate compression method (the only one supported in this version).

#define Z_DEFLATED 8

But PHP's function name zlib_encode() and define ZLIB_ENCODING_RAW seem to suggest zlib does support it ? If so what function and/or parameters do I use ?

Upvotes: 0

Views: 652

Answers (1)

Mark Adler
Mark Adler

Reputation: 112239

The PHP designations are (as usual) confusing. I will assume that ZLIB_ENCODING_RAW means raw deflate data (per RFC 1951), and it appears that ZLIB_ENCODING_DEFLATE actually means zlib-wrapped deflate data (per RFC 1950).

If that's correct, they should have called them ZLIB_ENCODING_DEFLATE and ZLIB_ENCODING_ZLIB, respectively. But I digress.

You can decode raw deflate data with the zlib library by using inflateInit2() instead of inflateInit(), and giving -15 as the second argument.

Upvotes: 1

Related Questions