Engineering

GZIP compression via PHP: don’t do it.

Why you should leave gzip content encoding to your web server

Recently, we’ve noticed that some WordPress plugins encode their responses with GZIP compression. As a result, we decided to write a short blurb as to why we think it should be avoided.

Reasons to avoid GZIP compression via PHP:

  1. Web servers are typically better at handling content encoding.
    • The typical flow for encoding a response with GZIP compression in PHP results in storing the original response and the encoded result in memory before sending it out in the response. This results in additional memory usage.
    • Most web servers, including WordFleet’s WordProxy, stream the encoding process as they read the response from your PHP script. Streaming in this context means that the process is done in smaller chunks, resulting in less memory usage overall.
  2. Modern web servers, including WordFleet’s WordProxy, can utilize newer encoding mechanisms such as Brotli. This offers faster encoding and better compression ratios. By forcing GZIP, or the current encoding algorithm du jour, developers are “un-future-proofing” their code.
  3. We’ve noticed some PHP plugins that do this fail to check if the client even accepts GZIP in the first place.
    • This can cause issues with clients that don’t accept GZIP encoding themselves.
    • If you must GZIP encode your response, just make sure to check the Accept-Encoding header for gzip support. This functionality is built into PHP via the ob_gzhandler function.

In summary, we recommend against encoding responses via PHP unless absolutely necessary. If you must, just ensure the client accepts the desired encoding before you do.