georg
georg

Reputation: 214959

Which function to deflate a http request?

I make a HTTP POST request to a remote service which requires the post body to be "deflated" (and Content-encoding: deflate should be sent in headers). From my understanding, this is covered in RFC 1950. Which php function should I use to be compatible?

Upvotes: 1

Views: 1348

Answers (1)

georg
georg

Reputation: 214959

Content-Encoding: deflate requires data to be presented using the zlib structure (defined in RFC 1950), with the deflate compression algorithm (defined in RFC 1951).

Consider

<?php
    $str = 'test';

    $defl = gzdeflate($str);
    echo bin2hex($defl), "\n";

    $comp = gzcompress($str);
    echo bin2hex($comp), "\n";
?>

This gives us:

2b492d2e0100
789c2b492d2e0100045d01c1

so the gzcompress result is the gzdeflate'd buffer preceded by 789c, which appears to be a valid zlib header

0111     |  1000       |  11100   |  0        |  10
CINFO    |  CM         |  FCHECK  |  FDICT    |  FLEVEL
7=32bit  |  8=deflate  |          |  no dict  |  2=default algo

and followed by 4 bytes of checksum. This is what we're looking for.

To sum it up,

  • gzdeflate returns a raw deflated buffer (RFC 1951)
  • gzcompress returns a deflated buffer wrapped in zlib stuff (RFC 1950)
  • Content-Encoding: deflate requires a wrapped buffer, that is, use gzcompress when sending deflated data.

Note the confusing naming: gzdeflate is not for Content-Encoding: deflate and gzcompress is not for Content-Encoding: compress. Go figure!

Upvotes: 4

Related Questions