1

I want convert a python code to php.

my problem is this line (python):

zlib.decompress( $gzipped, 16 + zlib.MAX_WBITS );

I don't know zlib.MAX_WBITS in php

my code (in php) :

$response = gzuncompress( $gzipped, ??? );
user3747500
  • 31
  • 1
  • 3
  • You can leave it blank, it's optional parameter – Unlink Jun 18 '14 at 10:39
  • this parameter is max length of decoding. here talks about it. [link]http://stackoverflow.com/questions/17021895/zlib-inflate-give-data-error-in-php .seems it is important – user3747500 Jun 18 '14 at 11:03

1 Answers1

1

Answer edited after feedback

It's a bit of a hassle, but you can do it with PHP compression filters.

$params = array('window' => 31);
$fp = fopen('your_data', 'rb');
stream_filter_append($fp, 'zlib.inflate', STREAM_FILTER_READ, $params);
print fread($fp, 1024);

The only problem is that you need to source the compressed data from a stream... I'm no PHP guy so I will leave that to you to figure out.

Original answer below for PHP >= 5.4.0

Short answer: try gzdecode() or zlib_decode() instead of gzuncompress().

Long answer...

In python (python 3):

>>> print(zlib.decompress.__doc__)
decompress(string[, wbits[, bufsize]]) -- Return decompressed string.

Optional arg wbits is the window buffer size.  Optional arg bufsize is
the initial output buffer size.
>>> print(zlib.MAX_WBITS)
15
>>> print(16 + zlib.MAX_WBITS)
31

This implies that the data was originally compressed using a window size of 31. In PHP the default window size for most zlib functions is 15, hence gzuncompress() and gzinflate() fail. However, it seems that gzdecode() and zlib_decode() do work ( I don't actually know why):

Compress using python3

>>> import zlib
>>> compressor = zlib.compressobj(wbits=(16+zlib.MAX_WBITS))
>>> compressed = compressor.compress(b'Here is a test string compressed by Python with a window size of 31\n')
>>> compressed += compressor.flush()
>>> compressed
b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\r\xca\xb1\r\x800\x0c\x04\xc0\x9e)~\x05\xc4\x12\x94\xac\x00\xe4!.\x12#\xdb\x92\x15\xa6\x87\xabo\xa5\x11\xe2\xd8\x11\xf4\x80\x87I\xbfqj{\x8c\xee,8\x06\xb6\x11U;R\xa2\xfe/\xa5\x17M\xb8\xbc\x84^X\xe6\xe9\x03\xabEV\xdbD\x00\x00\x00'
>>> open('/tmp/compressed', 'wb').write(compressed)
85

Decompress using PHP

php > $compressed = file_get_contents('/tmp/compressed');
php > print gzuncompress($compressed);
PHP Warning:  gzuncompress(): data error in php shell code on line 1
php > print gzinflate($compressed);
PHP Warning:  gzinflate(): data error in php shell code on line 1
php > print gzdecode($compressed);
Here is a test string compressed by Python with a window size of 31
php > print zlib_decode($compressed);
Here is a test string compressed by Python with a window size of 31
mhawke
  • 84,695
  • 9
  • 117
  • 138